I'm trying to implementing middleware for authorization.
main function :
func main() {
http.HandleFunc("/register", handlers.Register)
http.HandleFunc("/login", handlers.Login)
http.HandleFunc("/ex", middleware.RequireAuth(handlers.Ex))
http.ListenAndServe(":8080", nil)
}
middleware:
package middleware
import (
"context"
"net/http"
jwt "github.com/movie/JWT"
)
func RequireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, err := r.Cookie("authorization")
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
claims, err := jwt.ValidateToken(token.Value)
if err != nil {
http.Error(w, err.Error(), http.StatusNotAcceptable)
return
}
ctx := context.WithValue(r.Context(), "username", claims["username"])
next.ServeHTTP(w, r.WithContext(ctx))
})
}
handler:
func Ex(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hiihihihihi"))
}
This gives me an error.
cannot use middleware.RequireAuth(handlers.Ex) (value of type http.Handler) as func(http.ResponseWriter, *http.Request) value in argument to http.HandleFunc
How can I fix this?