在 HTTP 上添加中间件

我有这个 productHandler:


func productHandler(w http.ResponseWriter, r *http.Request) {

  var prop controller.Product

  switch r.Method {

    case "GET":

      prop.All()

  } [etc..]

}

然后我注册我的 productHandler


http.HandleFunc("/products/", productHandler)

如何将以下中间件添加到 HTTP 请求中?


func Accept(next http.Handler) http.Handler { 

  fc := func(w http.ResponseWriter, r *http.Request) {

    if r.Header.Get("Accept") != "application/json" {

      w.Write([]byte("Test M."))

      return

    }

  next.ServeHTTP(w, r)

  }

  return http.HandlerFunc(fc)

 }

如何将此中间件添加到我的所有处理程序中?


我试过了:


type Pr struct {

  handler http.Handler

}


func (p *Pr) ServeHttp(w http.ResponseWriter, r *http.Request) {

  a.handler.ServeHTTP(w, r)

  w.Write([]byte("Test M"))

}

我正在尝试在应用引擎 SDK 上实现这一点。


但它不起作用。


HUX布斯
浏览 222回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP