Go Web Frameworks interview question · Most asked

What is the http.Handler interface, and why is it central to Go web development?

Create a free account to save this page, take notes and track your progress. Sign in

Summary

http.Handler has one method, ServeHTTP(http.ResponseWriter, *http.Request). Routers, middleware, frameworks and servers all speak this interface, so pieces compose freely.

Longer Answer

http.HandlerFunc adapts a plain function to the interface. Middleware are functions func(http.Handler) http.Handler. Because Chi, Gin and Echo engines are themselves http.Handlers, they run under http.Server, test with httptest, and can host standard middleware.

Code Example

func logging(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Println(r.Method, r.URL.Path)
		next.ServeHTTP(w, r)
	})
}

Key Points

  • One method: ServeHTTP.
  • HandlerFunc adapts functions.
  • Middleware wrap handlers.
  • Frameworks are Handlers too (except Fiber).

Deep dive: Go Web Frameworks: Start with net/http

Explanation

What interviewers look for

Understanding the interface and how middleware composes around it.

More most-asked Go Web Frameworks questions

← All Go Web Frameworks questions

Was this page helpful?