function - 函数可以在 Go 中实现接口(interface)吗

标签 function go interface

我正在尝试制作类似于 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 type T ("x is assignable to T") in any of these cases:]

  • x's type V and T have identical underlying types and at least one of V or T is not a defined type.

关于function - 函数可以在 Go 中实现接口(interface)吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47509364/

相关文章:

oop - "interface"什么时候有用?

c - c中函数指针的工作

用于根据用户在另一个字段中的输入填充字段的 Javascript 函数

map - 如何在 Go 中使用任意长度的值序列作为映射键?

java - golang 中 key 长度为 15360 的 RSA key 对生成速度太慢。需要做些什么来解决这个问题?

go - foo.go + foo_test.go的任何有用替代方法

interface - typescript 支持 "subset types"吗?

javascript - 如何在 Javascript 中用单个变量编写多个参数?

c - 为什么在函数调用中找不到指针数组的大小?

events - 应该如何在 F# 接口(interface)中声明事件?