我有这个辅助函数,可以正常编译:
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/