我有一个简单的网络服务器的代码,但我不明白这段代码:
处理程序:app.routes(),
const webport = "80" type config struct {} func main() { app := config{} log.printf("starting broker service on port %sn",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 }
routes
是 config
结构体的一个方法。即使 config
为空,我们仍然可以像代码中那样调用 routes
方法。
cfg := Config{} r := cfg.routes()
config
结构在这里充当方法接收器。