简而言之,如果我为http.Request
运行一些中间件并确定该请求值得HTTP 422,那么我如何“跳出”中间件链,并在不调用链中所有中间件功能的情况下尽早返回?
例如,如果我有这个:
func Routes(m *martini.ClassicMartini) {
m.Get("/cp/users", mw.AsJson, mw.RequestTimer, ctr.GetMany)
}
如果我在上述任何中间件资金中调用
return
,据我所知,它仍将调用链中注册的所有中间件资金,因此总是会调用ctr.GetMany
。有什么方法可以使请求/响应完成,并告诉martini停止调用链中的所有func?
如果第一个返回值是整数,则我猜martini假设它是状态码。我目前最好的猜测是根据文档:
https://github.com/go-martini/martini#middleware-handlers
我们可以使用这个:
m.Use(func(c martini.Context, w http.ResponseWriter){
if reqIsMalformed() {
http.Error(w, "Bad request because xyz", 422)
return;
}
c.Next()
})
如果不满足条件,我们将永远无法调用
c.Next()
? 最佳答案
我用路由器/中间件做了一个实验,下面是结果(有用的信息在最后):
func check0() {
return
}
func check01() int {
return 200
}
func check02() (int, string) {
return 200, "boop"
}
func check03() bool {
return true
}
func check04() string {
return "04"
}
func check1(res http.ResponseWriter) string {
return "1"
}
func check2(c martini.Context, res http.ResponseWriter) string {
if true {
return "hiii"
}
c.Next()
return "2"
}
func check3(c martini.Context, res http.ResponseWriter) string {
c.Next()
return "3"
}
func check4(res http.ResponseWriter) {
res.Write([]byte("4"))
}
func check5(c martini.Context, res http.ResponseWriter) (int, string, string) {
res.Write([]byte("5.0"))
c.Next()
return 200, "5.1x", "5.1y"
}
func finish(res http.ResponseWriter) {
fmt.Println("in finish")
res.Write([]byte("all done"))
}
func Routes(m *martini.ClassicMartini) {
m.Get("/cp/meta/test/middleware0", check0, finish)
m.Get("/cp/meta/test/middleware01", check01, finish)
m.Get("/cp/meta/test/middleware02", check02, finish)
m.Get("/cp/meta/test/middleware03", check03, finish)
m.Get("/cp/meta/test/middleware04", check04, finish)
m.Get("/cp/meta/test/middleware1", check1, finish)
m.Get("/cp/meta/test/middleware2", check2, finish)
m.Get("/cp/meta/test/middleware3", check3, finish)
m.Get("/cp/meta/test/middleware4", check4, finish)
m.Get("/cp/meta/test/middleware5", check5, finish)
m.Get("/cp/meta/echo_runtime_config", common.AsJson, common.RequestTimer, mw.BodyToMap, ctr.GetRuntimeConfig)
}
这是我按下api时的结果:
GET /cp/meta/test/middleware0 => 'all done'
GET /cp/meta/test/middleware01 => ''
GET /cp/meta/test/middleware03 => '<bool Value>'
GET /cp/meta/test/middleware02 => 'boop'
GET /cp/meta/test/middleware1 => '1'
GET /cp/meta/test/middleware04 => '04'
GET /cp/meta/test/middleware2 => 'hiii'
GET /cp/meta/test/middleware3 => 'all done3'
GET /cp/meta/test/middleware4 => '4'
GET /cp/meta/test/middleware5 => '5.0all done5.1x'
本来应该添加到这个问题中。
所以这是规则:
关于go - 如何突破马提尼中间件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60679922/