我有这个产品手柄:
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"))
}
我正在尝试在app引擎SDK上实现这一点。
但它没有用。
答案 0 :(得分:1)
尝试http.Handle("/products/", Accept(http.HandlerFunc(productHandler)))
http://play.golang.org/p/mvclC4UUMV
package main
import (
"fmt"
"net/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)
}
func productHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
}
}
func main() {
http.Handle("/products/", Accept(http.HandlerFunc(productHandler)))
}