1. 7
  1.  

  2. 3

    Great article, and very approachable for go newcomers. I do have a couple ideas for enhancements/criticisms:

    • Tests could be added. The http testing story for go is very nice.
    • The datastore is racy. I recommend getting in the habit of running go test -race.

    Finally: I’ve never liked the implication behind: vars := mux.Vars(r) The implication is that there’s a global map/tree mapping requests to variable data. However that’s changing soon. Go1.7 will have a context object associated with the request. Gorilla has already updated their code to take advantage of it.

    1. 2

      We have to do this a lot for work (make restful JSON apis). To the point that I rolled up a bunch of our learnings into http://github.com/wcharczuk/go-web for my own side projects.

      Things to watch out for:
      * middleware! gzipping etc. there are a lot of really nice tools out there that plug right into the base net/http types.
      * testing can be tricky. the httptest utilities spin up a completely functioning server with their own go-routines etc. this can make things like sharing transactions between test => controller hard to manage.

      In go-web I created an app.Mock() function that spins up a request builder so you can throw things like query-string params and other state that your controller actions expect onto mock requests. It then resolves the path with the app’s router to test that you have things wired up with the mux correctly.

      an example:

      var res testCurrentUserResponse
      err = app.Mock().
          WithHeader(auth.SessionParamName, session.SessionID).
          WithPathf("/api/session.user").JSON(&res)
      
      assert.Nil(err)
      
      1. 1

        By all means, if anyone has suggestions for a better RESTful JSON API in Go, I’m all ears. I’m new to Go, but I’m totally in love with the simplicity of the example this guy has provided.