doucheng5705 2017-03-31 22:54
浏览 31
已采纳

服务器的Golang自定义处理程序

I want to use a custom method on http.ListenAndServe

Here is what I have

http.ListenAndServe(":8000", ErrorHandler)

func ErrorHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        h.ServeHTTP(w, r)
    })
}

Error

cannot use ErrorHandler (type func(http.Handler) http.Handler) as type http.Handler in argument to http.ListenAndServe:
        func(http.Handler) http.Handler does not implement http.Handler (missing ServeHTTP method)

How can I add a custom method to ListenAndServe?

  • 写回答

1条回答 默认 最新

  • doujianmin6527 2017-03-31 23:28
    关注

    Your ErrorHandler(h http.Handler) http.Handler func is basically just "middleware" and not a real handler. It takes a handler h and returns a new handler. http.StripPrefix is an example of such "middleware".

    If you don't want middleware, but just a handler then you need to define your function a little differently:

    func ErrorHandler(w http.ResponseWriter, r *http.Request) {
        // do stuff with r and w
    }
    

    Now you can pass your ErrorHandler to ListenAndServe although you still need to cast it to the proper http.Handler type like so:

    http.ListenAndServe(":8000", http.HandlerFunc(ErrorHandler))
    

    http.HandlerFunc is an adapter that turns a function, if it has the right signature, into an http.Handler.

    Finally, if you don't like the casting, you'll need to define a type instead of a just a function and you'll need to define a method on that type that is required for it to satisfy the http.Handler interface type.

    type ErrorHandler struct{}
    
    func (h *ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        // do stuff with r and w
    }
    
    http.ListenAndServe(":8080", &ErrorHandler{})
    

    Read more about it here https://golang.org/pkg/net/http/#Handler

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?