登录
首页 >  Golang >  Go问答

ServeHTTP 方法的由来

来源:stackoverflow

时间:2024-03-27 23:36:25 419浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《ServeHTTP 方法的由来》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

这让我在学习 go 的最后一个月里感到困惑:

func Auth(next http.HandlerFunc) http.HandlerFunc {

    return func(w http.ResponseWriter, r *http.Request) {  // hmmmm

        // ...
        next.ServeHTTP(w, r)
    }
}

在这里我们可以看到auth函数返回类型http.handlerfunc。 该类型只是一个函数。那么,当您调用 next.servehttp 时,该方法是在何时/何处定义的?


解决方案


https://golang.org/src/net/http/server.go?s=59707:59754#L1950

// 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)
}

从字面上看,任何具有签名 func(responsewriter, *request) 的函数都可以转换为 handlerfunc,这为其提供了方法 servehttp - 然后只需调用该函数即可。

好了,本文到此结束,带大家了解了《ServeHTTP 方法的由来》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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