[英]httprouter pass in many middleware functions
I'm coming from node express, and I was able to pass in as many middleware as possible, for example: routes.use('/*', ensureAuth, logImportant, ... n);
我来自 node express,我能够传入尽可能多的中间件,例如:
routes.use('/*', ensureAuth, logImportant, ... n);
How can I do something similar when using r.GET("/", HomeIndex)
?使用
r.GET("/", HomeIndex)
时如何做类似的事情?
Am I forced to do something like EnsureAuth(HomeIndex)
?我是否被迫做类似
EnsureAuth(HomeIndex)
事情? Because I can get that to work.因为我可以让它发挥作用。 Unfortunately, I'm not sure what would be a good way to add as many middlewares as I want without chaining functions together.
不幸的是,我不确定在不将函数链接在一起的情况下添加任意数量的中间件的好方法是什么。
Is there a more elegant way so I could somehow use variadic type function to do r.GET("/", applyMiddleware(HomeIndex, m1, m2, m3, m4)
? I'm trying that out right now, but I feel like there's a better way to do this.有没有更优雅的方法,所以我可以以某种方式使用可变参数类型函数来执行
r.GET("/", applyMiddleware(HomeIndex, m1, m2, m3, m4)
?我现在正在尝试,但我觉得有更好的方法来做到这一点。
I've looked at the httprouter issues page, can't find anything :(我查看了 httprouter 问题页面,找不到任何内容:(
Thanks!谢谢!
Here is an example how I did it:这是我如何做到的一个例子:
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))
}
Link to code (you can't run it from play.golang.org
though): https://play.golang.org/p/BOCt97xcoY代码链接(虽然你不能从
play.golang.org
运行它): https : //play.golang.org/p/BOCt97xcoY
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.