登录
首页 >  Golang >  Go问答

serveHTTP在裸函数中的来源是什么?

来源:stackoverflow

时间:2024-02-27 17:09:26 236浏览 收藏

一分耕耘,一分收获!既然都打开这篇《serveHTTP在裸函数中的来源是什么?》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我有这个实用程序:

type handler struct{}

func (h handler) mount(router *mux.router, v peopleinjection) {
    router.handlefunc("/api/v1/people", h.makegetmany(v)).methods("get")
}

上面的调用是:

func (h handler) makegetmany(v peopleinjection) http.handlerfunc {

    type respbody struct {}

    type reqbody struct {
        handle string
    }

    return tc.extracttype(
        tc.typelist{reqbody{},respbody{}},
        func(w http.responsewriter, r *http.request) {
         // ...
    })
}

然后 tc.extracttype 如下所示:

func extracttype(s typelist, h http.handlerfunc) http.handlerfunc {

    return func(w http.responsewriter, r *http.request) {

        h.servehttp(w, r)  // <<< h is just a func right? so where does servehttp come from?
    }
}

我的问题是——servehttp 方法/函数从哪里来?

h 参数不就是一个带有此签名的函数吗:

func(w http.responsewriter, r *http.request) { ... }

那么该函数如何附加 servehttp 函数呢?

换句话说,我为什么打电话

h.servehttp(w,r)

而不是

h(w,r)


解决方案


http.HandlerFunc 是表示 func(responsewriter, *request) 的类型。

http.handlerfuncfunc(responsewriter, *request) 之间的区别是:http.handlerfunc 类型有名为 servehttp() 的方法。

来自source code

// 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.
type handlerfunc func(responsewriter, *request)

// servehttp calls f(w, r).
func (f handlerfunc) servehttp(w responsewriter, r *request) {
    f(w, r)
}

http.handlerfunc() 可用于包装处理函数。

func something(next http.handler) http.handler {
    return http.handlerfunc(func(w http.responsewriter, r *http.request) {
        // do something

        next.servehttp(w, r)
    })
}

包装的处理程序将具有 http.handlerfunc() 类型,这意味着我们将能够访问它的 .servehttp() 方法。

还有另一种类型,名为 http.Handler 的接口。它具有 .servehttp() 方法签名,并且必须在嵌入该接口的结构体上实现。

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

正如您在上面的 something() 函数中看到的,需要 http.handler 类型的返回值,但我们返回了一个包装在 http.handlerfunc() 中的处理程序。没关系,因为 http.handlerfunc 有方法 .servehttp() 满足 http.handler 接口的要求。

因为要继续服务传入的请求,您需要调用 .servehttp()

到这里,我们也就讲完了《serveHTTP在裸函数中的来源是什么?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>