douhe4336 2019-07-14 08:57
浏览 167
已采纳

应该返回Handler的函数如何返回HandlerFunc?

While chaining handlers, the function has a return type of Handler, but it actually returns a HandlerFunc. This does not throw any error.

How is HandlerFunc accepted in place of a Handler, the prior being a function type and the latter being a interface type?

func log(h http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    ...
  })
}
  • 写回答

2条回答 默认 最新

  • doufuxing8562 2019-07-14 09:06
    关注

    The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

    The http.Handler is an interface:

    type Handler interface {
        ServeHTTP(ResponseWriter, *Request)
    }
    

    The http.HandlerFunc is a type:

    type HandlerFunc func(ResponseWriter, *Request)
    
    // ServeHTTP calls f(w, r).
    func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
        f(w, r)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥15 第一个已完成,求第二个做法
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?