Go Web Packages

This is not about framework vs library.

In Go, a framework or a library is just a package.

This post is just a short guide to understand Go web packages.

First up, some definitions:

A framework calls your code, you call library code.

Second, per Nicolas Merouze, a Web framework has three parts:

  1. A router receiving a request and directing it to a handler
  2. a middleware system to add reusable pieces of software before and after the handler
  3. the handler processing the request and writing the response.

Third, this is how Go defines standard HTTP handler.

  1. func handler(w http.ResponseWriter, r *http.Request) {
      fmt.Fprintf(w, "Welcome!")
    }
    
    func main() {
      http.HandleFunc("/", handler)
      http.ListenAndServe(":8080", nil)
    }
  2. type handler struct {}
    
    func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Welcome!")
    }
    
    func main() {
      http.Handle("/", handler)
      http.ListenAndServe(":8080", nil)
    }

If you want to build your own Web framework in Go, here are some notes:

  • router – standard net/http ServeMux, gorilla vs pat vs routes, httprouter, Goji built its own router out of frustration with pat
  • middleware – middleware chaining with alice or siesta. Your choice of framework will affect the way you chain middleware (of course). With negroni, it is bring-your-own-router middleware

HTTP request context (aka share values between middleware)

  • global context map – used by gorilla/context. Uses mutex
  • per request map[string]interface – used by Goji (on-demand map allocation, needs a wrapper for HTTP handler)
  • context struct – used by gocraft/web (no mutex, no type assertion but not compatible with standard HTTP handler)
  • httpcontext

Bottomline:

In theory, you can mix and match Go packages. In practice, you need a wrapper if the package in question does not adhere to standard Go API.

For a list of Go code examples, go to https://github.com/ibmendoza/go-examples

Advertisements

Subjectivity aside, leave a reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s