1

I'm trying to understand the difference between handler.ServeHTTP(w,req) and handler(w,req) in Go testing. When should I use each of them? Are they exactly the same?

Docs say simply: ServeHTTP calls f(w, r).

for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
        request := httptest.NewRequest(http.MethodGet, "/status", nil)
        w := httptest.NewRecorder()
        h := http.HandlerFunc(handlers.StatusHandler)
      
        h.ServeHTTP(w, request)
        /// or should it be
        h(w, request)
        
        ...
    }
}
mishkamashka
  • 73
  • 1
  • 6
  • 3
    Yes, the two calls are the same. That's what the documentation says, and you can just look at the implementation: https://cs.opensource.google/go/go/+/refs/tags/go1.19.4:src/net/http/server.go;l=2108 – Peter Dec 27 '22 at 12:07
  • 1
    They are the same, use whichever you like best. – mkopriva Dec 27 '22 at 12:09

1 Answers1

1

As @peter and @mkopriva pointed out, the options are exactly the same and it's a matter of taste

mishkamashka
  • 73
  • 1
  • 6