Go httprouter传递了许多中间件功能
我来自node express,能够传入尽可能多的中间件,例如:Go httprouter传递了许多中间件功能,go,middleware,httprouter,Go,Middleware,Httprouter,我来自node express,能够传入尽可能多的中间件,例如:routes.use('/*',ensureAuth,logImportant,…n) 使用r.GET(“/”,HomeIndex)时如何执行类似操作 我是否被迫执行类似于EnsureAuth(HomeIndex)的操作?因为我可以让它工作。不幸的是,我不确定在不将函数链接在一起的情况下,添加尽可能多的中间件的好方法是什么 有没有一种更优雅的方法可以让我用变量类型的函数来做r.GET(“/”),applyMiddleware(Hom
routes.use('/*',ensureAuth,logImportant,…n)代码>
使用r.GET(“/”,HomeIndex)
时如何执行类似操作
我是否被迫执行类似于EnsureAuth(HomeIndex)
的操作?因为我可以让它工作。不幸的是,我不确定在不将函数链接在一起的情况下,添加尽可能多的中间件的好方法是什么
有没有一种更优雅的方法可以让我用变量类型的函数来做r.GET(“/”),applyMiddleware(HomeIndex,m1,m2,m3,m4)
?我现在正在尝试,但我觉得有更好的方法来做这件事
我查看了httprouter问题页面,没有找到任何内容:(
谢谢!以下是我如何做到这一点的示例:
package main
import (
"context"
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/justinas/alice"
)
// m1 is middleware 1
func m1(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//do something with m1
log.Println("m1 start here")
next.ServeHTTP(w, r)
log.Println("m1 end here")
})
}
// m2 is middleware 2
func m2(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//do something with m2
log.Println("m2 start here")
next.ServeHTTP(w, r)
log.Println("m2 end here")
})
}
func index(w http.ResponseWriter, r *http.Request) {
// get httprouter.Params from request context
ps := r.Context().Value("params").(httprouter.Params)
fmt.Fprintf(w, "Hello, %s", ps.ByName("name"))
}
// wrapper wraps http.Handler and returns httprouter.Handle
func wrapper(next http.Handler) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
//pass httprouter.Params to request context
ctx := context.WithValue(r.Context(), "params", ps)
//call next middleware with new context
next.ServeHTTP(w, r.WithContext(ctx))
}
}
func main() {
router := httprouter.New()
chain := alice.New(m1, m2)
//need to wrap http.Handler to be compatible with httprouter.Handle
router.GET("/user/:name", wrapper(chain.ThenFunc(index)))
log.Fatal(http.ListenAndServe(":9000", router))
}
链接到代码(您不能从play.golang.org
运行它):只是一个问题,您是否严格需要httprouter?我是新手,我读了一些文章,读到了JSON api httprouter将具有快速性能和易用性。您的中间件如何,它们是否属于此签名func(http.Handler)http.Handler
?是的。我返回httprouter.Handle
,并传入httprouter.Handle
类型的Handle
。看看这个包是否可以帮助您