gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:19 26 4
gpt4 key购买 nike

在链接处理程序时,该函数的返回类型为 Handler,但它实际上返回一个 HandlerFunc。这不会引发任何错误。

如何接受 HandlerFunc 代替 Handler,前者是函数类型,后者是接口(interface)类型?

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

最佳答案

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.

http.Handler 是一个接口(interface):

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

http.HandlerFunc 是一个类型:

type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}

关于go - 应该返回 Handler 的函数如何返回 HandlerFunc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57025911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com