英文:
golang dont understand how http.Server Handler calling functions which attahced to empty struct
问题
这段代码是一个简单的Web服务器。让我来解释一下。
首先,代码中的Handler: app.routes()
是在创建http.Server
时设置的处理程序。app.routes()
是一个方法,它返回一个http.Handler
,用于处理传入的HTTP请求。
在routes
文件中,func (app *Config) routes() http.Handler
是一个方法的定义。它的接收者是app *Config
,表示该方法是与Config
类型相关联的。这意味着只有Config
类型的实例才能调用这个方法。
在main
函数中,app := Config{}
创建了一个Config
类型的实例app
。然后,app.routes()
被调用并作为处理程序传递给http.Server
。
所以,app
实例调用了routes
方法,这就是为什么routes
方法能够被触发的原因。
英文:
i have this code of simple web server but i dont understand this code :
Handler: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)
}
}
and in routes file :
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
}
this is wroking and the routes() function called when request recived
but how does this routes() knows to be triggered when it attached to empty struct
app := Config{}
from where does app knows about routes() ?
what is the :
func (app *Config)
in the function ?
答案1
得分: 3
路由已附加到HTTP服务器,如下所示。
srv := &http.Server{
Addr: ":8081", // 端口
Handler: app.routes() // 调用的处理程序
}
routes
是 Config
结构体的一个方法。即使 Config
是空的,我们仍然可以像你的代码中一样调用 routes
方法。
cfg := Config{}
r := cfg.routes()
在这里,Config
结构体充当方法接收器。
英文:
Routes have been attached to the HTTP server as shown below.
srv := &http.Server{
Addr: ":8081", // port
Handler: app.routes() // a handler to invoke
}
routes
is a method of Config
struct. We can still call the routes
methods as in your code even when Config
is empty.
cfg := Config{}
r := cfg.routes()
Config
struct is acting as a method receiver here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论