doudan5136 2017-11-27 11:01
浏览 40
已采纳

功能可以在Go中实现接口

I'm trying to make an interface similar to http.Handler. For certain endpoints of my API I need a APNS token included in the query or I need to respond with http.StatusBadRequest.

I want the type DeviceHandlerFunc to implement ServeHTTP(http.ResponseWriter, *http.Request) and automatically parse the token and call itself with the 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)
    }
}

Then from 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...
}

This causes a compiler error:

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)

In my mind I couldn't be more clear that the type func(http.ResponseWriter, *http.Request, string) implements http.Handler. What am I doing wrong?

Sample code as playground.

  • 写回答

1条回答 默认 最新

  • doukangbin9698 2017-11-27 11:05
    关注

    Your DeviceHandlerFunc type indeed implements http.Handler. That's not the problem.

    But your getDevice() function is not of type DeviceHandlerFunc, it's of type func(http.ResponseWriter, *http.Request, string) (which is an unnamed type which obviously does not implement http.Handler).

    To make it work, use a simple type conversion:

    mux.Handle("/", DeviceHandlerFunc(getDevice))
    

    You can convert getDevice to DeviceHandlerFunc as the underlying type of DeviceHandlerFunc is the same as the type of getDevice. Try it on the Go Playground.

    The following would also work:

    var f DeviceHandlerFunc = getDevice
    mux.Handle("/", f)
    

    Here type of f is obviously DeviceHandlerFunc. And you can assign getDevice to f as assignability rules apply, namely this one:

    [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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形