Golang / GoLang Interfaces and Object Oriented Interview Questions
How does http.Handler demonstrate real-world interface design in Go?
http.Handler is one of Go's most widely used interfaces. It models exactly one behaviour — handling an HTTP request — with a single method. The entire net/http server is built around this interface, making it extensible, testable, and composable through middleware.
// The entire http.Handler interface: type Handler interface { ServeHTTP(ResponseWriter, *Request) } // Implement it on a struct type HelloHandler struct{ Greeting string } func (h HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "%s, %s!", h.Greeting, r.URL.Query().Get("name")) } http.Handle("/hello", HelloHandler{Greeting: "Hello"}) // http.HandlerFunc â adapter: converts a function to a Handler func greetFunc(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hi!") } http.Handle("/greet", http.HandlerFunc(greetFunc)) // function cast to HandlerFunc // Middleware pattern â wraps a Handler with cross-cutting concerns func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() next.ServeHTTP(w, r) // call the inner handler log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start)) }) } func authMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("X-Token") == "" { http.Error(w, "unauthorized", 401) return } next.ServeHTTP(w, r) }) } // Chain middleware handler := loggingMiddleware(authMiddleware(HelloHandler{Greeting: "Hello"})) http.Handle("/secure", handler)
http.HandlerFunc is a named function type that satisfies http.Handler. It is a classic Go pattern: define a named type on a function signature, then implement the interface on that type. This converts any compatible function into an interface implementor — zero overhead, no wrapper struct needed.
More Related questions...