1

Go ブログ: エラー処理と GoappHandlerで説明されているように実装しようとしています。私は を持っています。今はそれを自分のルートに接続しようとしています。以下の作品:appHandler

router := new(mux.Router)
router.Handle("/my/route/", handlers.AppHandler(handlers.MyRoute))

しかし、「StrictSlash(true)」を持つだけでなく、GET リクエストを許可できるようにしたいと考えています。私は持っている:

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
4

1 に答える 1

0

あなたAppHandlerは ではありませんhttp.HandlerFunc、それはhttp.Handlerです。

Aは、 aと 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)
}
于 2015-05-28T04:18:49.863 に答える