【发布时间】:2018-05-10 14:22:44
【问题描述】:
我正在尝试制作一个类似于http.Handler 的界面。对于我的 API 的某些端点,我需要在查询中包含一个 APNS 令牌,或者我需要回复 http.StatusBadRequest。
我想让DeviceHandlerFunc类型实现ServeHTTP(http.ResponseWriter, *http.Request)并自动解析token并用token调用自己:
type DeviceHandlerFunc func(http.ResponseWriter, *http.Request, string)
func (f DeviceHandlerFunc) ServeHTTP(res http.ResponseWriter, req *http.Request) {
token := req.URL.Query().Get("token")
if token == "" {
http.Error(res, "token missing from query", http.StatusBadRequest)
} else {
f(res, req, token)
}
}
然后来自main.go:
func main() {
mux := http.NewServeMux()
mux.Handle("/", getDevice)
log.Fatal(http.ListenAndServe(":8081", mux))
}
func getDevice(res http.ResponseWriter, req *http.Request, token string) {
// Do stuff with token...
}
这会导致编译器错误:
main.go:22:13: cannot use getDevice (type func(http.ResponseWriter, *http.Request, string)) as type http.Handler in argument to mux.Handle:
func(http.ResponseWriter, *http.Request, string) does not implement http.Handler (missing ServeHTTP method)
在我看来,func(http.ResponseWriter, *http.Request, string) 类型实现了http.Handler,这一点我再清楚不过了。我做错了什么?
示例代码as playground。
【问题讨论】: