我有这个辅助函数,可以正常编译:
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
有谁知道为什么在这种情况下该类型断言会失败?没有意义。也许我实际上并没有检索切片的最后一个参数之类的?有没有更好的方法从切片中弹出最后一个参数?
函数式编程
catspeake
相关分类