2 回答
TA贡献1858条经验 获得超8个赞
notorious.no 提供的解决方案也非常适合给定的要求。我还遇到了另一个使用 PathPrefix 并解决相同问题的解决方案,并希望获得相同的建议。
// create a serve mux
sm := mux.NewRouter()
// register handlers
postR := sm.Methods(http.MethodPost).Subrouter()
postR.HandleFunc("/signup", uh.Signup)
postR.HandleFunc("/login", uh.Login)
postR.Use(uh.MiddlewareValidateUser)
refToken := sm.PathPrefix("/refresh-token").Subrouter()
refToken.HandleFunc("", uh.RefreshToken)
refToken.Use(uh.MiddlewareValidateRefreshToken)
getR := sm.Methods(http.MethodGet).Subrouter()
getR.HandleFunc("/greet", uh.Greet)
getR.Use(uh.MiddlewareValidateAccessToken)
使用参考来到这个解决方案:https ://github.com/gorilla/mux/issues/360
TA贡献1862条经验 获得超7个赞
我有一个类似的用例,这是我如何解决它的一个例子:
package main
import (
"log"
"net/http"
"time"
)
import (
"github.com/gorilla/mux"
)
// Adapter is an alias so I dont have to type so much.
type Adapter func(http.Handler) http.Handler
// Adapt takes Handler funcs and chains them to the main handler.
func Adapt(handler http.Handler, adapters ...Adapter) http.Handler {
// The loop is reversed so the adapters/middleware gets executed in the same
// order as provided in the array.
for i := len(adapters); i > 0; i-- {
handler = adapters[i-1](handler)
}
return handler
}
// RefreshToken is the main handler.
func RefreshToken(res http.ResponseWriter, req *http.Request) {
res.Write([]byte("hello world"))
}
// ValidateRefreshToken is the middleware.
func ValidateRefreshToken(hKey string) Adapter {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
// Check if a header key exists and has a value
if value := req.Header.Get(hKey); value == "" {
res.WriteHeader(http.StatusForbidden)
res.Write([]byte("invalid request token"))
return
}
// Serve the next handler
next.ServeHTTP(res, req)
})
}
}
// MethodLogger logs the method of the request.
func MethodLogger() Adapter {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
log.Printf("method=%s uri=%s\n", req.Method, req.RequestURI)
next.ServeHTTP(res, req)
})
}
}
func main() {
sm := mux.NewRouter()
getR := sm.Methods(http.MethodGet).Subrouter()
getR.HandleFunc("/refresh-token", Adapt(
http.HandlerFunc(RefreshToken),
MethodLogger(),
ValidateRefreshToken("Vikee-Request-Token"),
).ServeHTTP)
srv := &http.Server{
Handler: sm,
Addr: "localhost:8888",
WriteTimeout: 30 * time.Second,
ReadTimeout: 30 * time.Second,
}
log.Fatalln(srv.ListenAndServe())
}
该Adapt函数允许您将多个处理程序链接在一起。我已经演示了 2 个中间件函数(ValidateRefreshToken和MethodLogger)。中间件基本上是闭包。您可以将此方法与任何接受http.Handler诸如mux和的框架一起使用chi。
- 2 回答
- 0 关注
- 109 浏览
添加回答
举报