如何将我的AppHandler添加到我的路线?

时间:2015-05-28 03:00:33

标签: go gorilla

我正在尝试按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

1 个答案:

答案 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
}