如何将我的 AppHandler 添加到我的路由中?

How do I add my AppHandler to my routes?

我正在尝试实现 appHandler,如 The Go Blog: Error handling and Go 中所述。 我有 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

你的 AppHandler 不是 http.HandlerFunc,而是 http.Handler

A http.HandlerFunc 只是一个同时接受 http.ResponseWriter*http.Request 的函数。

http.Handler 是任何具有方法 ServeHTTP(w http.ResponseWriter, r *http.Request)

的类型都满足的接口

将您的结构更改为

type Route struct {
    Method  string
    Pattern string
    Handler http.Handler
}

然后在底部你可能会做

for _, route := range routes {
    router.Methods(route.Method).Path(route.Pattern).Handler(route.Handler)
}