[zeromicro/go-zero]中间件怎么返回400状态码

2024-01-12 121 views
5

return func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadRequest) return }

加了这样的代码,但前端接收到还是200的状态码,中间件w.WriteHeader(http.StatusBadRequest) return 代码无效

回答

9

给出完整代码哈,这看不出来是不是使用错误。

7
示例代码

server.Use(BadRequestHandler)

func BadRequestHandler(next http.HandlerFunc) http.HandlerFunc {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
          w.WriteHeader(http.StatusBadRequest)
          return
    })
}
7

func Handle(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { http.Error(w, "无效请求", http.StatusBadRequest) return } }

我知道怎么弄了