go - panic : Last argument needs to be of type 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

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

 length of adapters:2

有人知道为什么在这种情况下该类型断言会失败吗?没有意义。也许我实际上并没有检索 slice 的最后一个参数之类的?有没有更好的方法从 slice 中弹出最后一个参数?

最佳答案

您需要使用 http.HandlerFunc()mw.Middleware() 语句的第二个参数包装到 http.Handler 类型中.

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

关于go - panic : Last argument needs to be of type http. HandlerFunc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53862864/

相关文章:

sorting - 带重音符号的字符串键的排序结构

ubuntu - 服务器上的简单 go 二进制部署不起作用

go - net/url 包根据请求查询参数添加换行符

templates - 模板对象字段强制执行

colors - 使用 Color 包从 RGB 值创建新的颜色?

arrays - Go 中这两种 "slice copy"方法有什么区别

web-services - 在 Go (golang) 中使用网络服务器显示 gif 图像

Golang rest api并发

android - Make Go http.Response 详细说明所有参数

go - 如何检查 slice 界面元素是否具有相同的动态类型?