我正在尝试制作类似于 http.Handler
的界面.对于我的 API 的某些端点,我需要在查询中包含一个 APNS token ,或者我需要使用 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 .
最佳答案
您的 DeviceHandlerFunc
类型确实实现了 http.Handler
.这不是问题。
但是您的getDevice()
函数不是 DeviceHandlerFunc
类型,它是func(http.ResponseWriter, *http .Request, string)
(这是一个未命名的类型,显然没有实现 http.Handler
)。
要使其工作,请使用简单类型 conversion :
mux.Handle("/", DeviceHandlerFunc(getDevice))
您可以将 getDevice
转换为 DeviceHandlerFunc
,因为 DeviceHandlerFunc
的基础类型与 getDevice
的类型相同>。在 Go Playground 上试用.
以下也可以:
var f DeviceHandlerFunc = getDevice
mux.Handle("/", f)
这里f
的类型显然是DeviceHandlerFunc
。您可以将 getDevice
分配给 f
作为 assignability规则适用,即这个:
[A value
x
is assignable to a variable of typeT
("x
is assignable toT
") in any of these cases:]
x
's typeV
andT
have identical underlying types and at least one ofV
orT
is not a defined type.
关于function - 函数可以在 Go 中实现接口(interface)吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47509364/