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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
