dreamy6301 2018-12-20 05:27
浏览 68
已采纳

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

I have this helper function, which is compiling fine:

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

}

I am calling it like so:

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)
        },
    )
}

the problem is that I am getting this error and I cannot figure out why:

    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

it does confirm that the length of the adapters slice is 2:

 length of adapters:2

anyone know why that type assertion would fail in this case? Makes no sense. Maybe I am not actually retrieving the last argument of the slice or something? Is there a better way to pop the last argument off the slice?

  • 写回答

2条回答 默认 最新

  • douxie2023 2018-12-20 05:37
    关注

    You need to wrap the 2nd argument of mw.Middleware() statement into http.Handler type by using 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)
            }),
        )
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。