我正在尝试按The Go Blog: Error handling and Go中所述实施appHandler
。
我有appHandler
,现在我只想把它连接到我的路线上。以下作品:
router := new(mux.Router)
router.Handle("/my/route/", handlers.AppHandler(handlers.MyRoute))
但是,我希望能够允许GET请求以及“StrictSlash(true)”。我有:
type Routes []Route
type Route struct {
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
var routes = Routes{
Route{"GET", "/my/route/", handlers.AppHandler(handlers.MyRoute)}
}
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
router.Methods(route.Method).Path(route.Pattern).Handler(handler)
}
AppHandler看起来像:
type AppHandler func(http.ResponseWriter, *http.Request) *appError
func (fn AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// blah, blah, blah
}
我收到错误:
cannot use handlers.AppHandler(handlers.MyRoute) (type handlers.AppHandler) as type http.HandlerFunc in field value
答案 0 :(得分:0)
您的AppHandler
不是http.HandlerFunc
,而是http.Handler
。
http.HandlerFunc
只是同时采用{{1}}和http.ResponseWriter
的函数。
*http.Request
是具有方法http.Handler
将您的结构更改为
ServeHTTP(w http.ResponseWriter, r *http.Request)
然后在底部你可以做
type Route struct {
Method string
Pattern string
Handler http.Handler
}