Structuring Applications in Go
Ben Johnson
3889

Hi Ben Johnson,

Thank you so much for such a nice post. I am Java developer in my day job but evenings are for Golang — I haven’t really started writing bigger Go apps — it’s limited to the main package right now. Thank you so much for this post — it makes a lot of sense.

I went though the wrapping your handlers with a closure gist as well as Tomas Senart’s talk I think in GopherCon and that seemed logical as well. I was just wondering if there is a guideline to test out these HTTP closures?

Is this how this handler can be tested?

// test
func TestHelloHandler(t *testing.T) {

// Open our connection and setup our handler.
db, _ := db.Open(...)
defer db.Close()

// Execute our handler with a simple buffer.
rec := httptest.NewRecorder()
rec.Body = bytes.NewBuffer()

//need to figure out how to test this...
thisIsTheHandlerWeNeedToTest := helloHandler(db)
req, _ := http.NewRequest("GET", "", nil)
thisIsTheHandlerWeNeedToTest.ServeHTTP(rec, req)

if rec.Body.String() != "hi bob!\n" {
t.Errorf("unexpected response: %s", rec.Body.String())
}
}
assuming “helloHandler” is defined like this:
func helloHandler(db *sql.DB) http.Handler { 
 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

Thanks again for such a helpful post.

Show your support

Clapping shows how much you appreciated Ritwick Ghosh’s story.