将您的授权中间件重新实现为
http.Handler:
type auth struct { DB *sql.DB UnauthorizedHandler http.Handler}func NewAuth(db *sql.DB, unauthorized http.Handler) *auth { return auth{db, unauthorized}}func (a *auth) Protected(h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { // Check whether the request is valid // If it's invalid, call your error func and make sure to *return* early! if !valid { a.UnauthorizedHandler.ServeHTTP(w, r) return } // Call the next handler on success h.ServeHTTP(w, r) return } return http.HandlerFunc(fn)}func someHandler(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello!n")}func main() { auth := NewAuth(db, errorHandler) r := http.NewServeMux() // We have a http.Handler implementation that wraps a http.HandlerFunc // ... so we call r.Handle on our ServeMux and type-cast the wrapped func r.Handle("/protected", auth.Protected(http.HandlerFunc(someHandler))) // Just a simple http.HandlerFunc here r.HandleFunc("/public", someOtherHandler) log.Fatal(http.ListenAndServe(":8000", r))}Take a look at the httpauth lib I
wrote for a
different example with a
ServeHTTPmethod. Both the above and explicitly
creating a
ServeHTTPmethod on your type are valid approaches.



