登录
首页 >  Golang >  Go问答

Go:如何调用附加到空结构的函数,以及 http.Server Handler 的工作原理解析

来源:stackoverflow

时间:2024-02-16 16:48:23 168浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《Go:如何调用附加到空结构的函数,以及 http.Server Handler 的工作原理解析》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

问题内容

我有一个简单的网络服务器的代码,但我不明白这段代码:

处理程序:app.routes(),

const webport = "80"

type config struct {}

func main() {

    app := config{}
    log.printf("starting broker service on port %s\n",webport)
    srv := &http.server{
        addr: fmt.sprintf(":%s",webport),
        handler:app.routes(),
    }

    err := srv.listenandserve()
    if(err != nil) {
        log.panic(err)
    }
}

在路由文件中:

func (app *config) routes() http.handler {
    mux := chi.newrouter()
    mux.use(cors.handler(cors.options{
        allowedorigins: []string{"http://*","https://*"},
        allowedmethods: []string{"get", "post", "delete","put","options"},
        allowedheaders: []string{"accept","authorization","content-type","x-csrf-token"},
        exposedheaders: []string{"link"},
        allowcredentials:true,
        maxage:300,
    }))

    mux.use(middleware.heartbeat("/ping"))
    mux.post("/",app.broker)

    return mux
}

这是有效的,当收到请求时调用的routes()函数, 但是这个routes()如何知道当它附加到一个空结构时被触发呢?

app := Config{}

应用程序从哪里知道routes()?

函数中的 func (app *config) 是什么?


正确答案


路由已附加到 http 服务器,如下所示。

srv := &http.server{
   addr: ":8081", // port
   handler: app.routes() // a handler to invoke
 }

routesconfig 结构体的一个方法。即使 config 为空,我们仍然可以像代码中那样调用 routes 方法。

 cfg := Config{}
 r := cfg.routes()

config 结构在这里充当方法接收器。

以上就是《Go:如何调用附加到空结构的函数,以及 http.Server Handler 的工作原理解析》的详细内容,更多关于的资料请关注golang学习网公众号!

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