http.Handler là interface chỉ có một method:
go
type Handler interface {
ServeHTTP(w http.ResponseWriter, r *http.Request)
}http.HandlerFunc là một kiểu hàm có sẵn method ServeHTTP gọi lại chính nó — nhờ vậy một hàm thường có thể đóng vai Handler mà không cần định nghĩa struct riêng:
go
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { f(w, r) }Thực tế:
go
func hello(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hi")) }
mux := http.NewServeMux()
mux.Handle("/a", http.HandlerFunc(hello)) // ép hàm thành Handler
mux.HandleFunc("/b", hello) // đường tắt, bên trong làm đúng việc trênÝ nghĩa khi phỏng vấn: mọi thứ trong net/http (router, middleware, http.FileServer, http.StripPrefix) đều nói chuyện qua một interface duy nhất này, nên middleware chỉ là hàm func(http.Handler) http.Handler.
Khi cần handler mang state (DB pool, logger, config) thì dùng struct có method ServeHTTP, hoặc closure bắt biến.