小编典典

恐慌:最后一个参数必须为http.HandlerFunc类型

go

我有这个辅助函数,可以正常编译:

func Middleware(adapters ...interface{}) http.HandlerFunc {

    log.Info("length of adapters:", len(adapters))

    if len(adapters) < 1 {
        panic("Adapters need to have length > 0.");
    }

    h, ok := (adapters[len(adapters)-1]).(http.HandlerFunc)

    if ok == false {
        panic("Last argument needs to be of type http.HandlerFunc") // ERROR HERE
    }

    adapters = adapters[:len(adapters)-1]

    for _, adapt := range adapters {
        h = (adapt.(AdapterFunc))(h)
    }

    return h

}

我这样称呼它:

router.HandleFunc("/share", h.makeGetMany(v)).Methods("GET")

func (h Handler) makeGetMany(v Injection) http.HandlerFunc {
    return mw.Middleware(
        mw.Allow("admin"),
        func(w http.ResponseWriter, r *http.Request) {
            log.Println("now we are sending response.");
            json.NewEncoder(w).Encode(v.Share)
        },
    )
}

问题是我收到此错误,但我无法弄清原因:

    panic: Last argument needs to be of type http.HandlerFunc

    goroutine 1 [running]:
    huru/mw.Middleware(0xc420083d40, 0x2, 0x2, 0xc42011f3c0)
            /home/oleg/codes/huru/api/src/huru/mw/middleware.go:301

+0x187
huru/routes/share.Handler.makeGetMany(0xc4200ae1e0, 0x10)
/home/oleg/codes/huru/api/src/huru/routes/share/share.go:62
+0x108

它确实确认适配器片的长度为2:

 length of adapters:2

有谁知道为什么这种类型的断言在这种情况下会失败?没有意义。也许我实际上不是在检索切片的最后一个参数或其他内容?是否有更好的方法可以将最后一个参数弹出切片?


阅读 266

收藏
2020-07-02

共1个答案

小编典典

您需要使用来将mw.Middleware()statement 的第二个参数包装为http.Handlertype
http.HandlerFunc()

func (h Handler) makeGetMany(v Injection) http.HandlerFunc {
    return mw.Middleware(
        mw.Allow("admin"),
        http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            log.Println("now we are sending response.");
            json.NewEncoder(w).Encode(v.Share)
        }),
    )
}
2020-07-02