Go 不理解 http.Server Handler 如何调用附加到空结构的函数

问题描述 投票:0回答:1

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

处理程序: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)
是什么?

go handler httpserver
1个回答
3
投票

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

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.