Golang不理解如何调用附加到空结构的函数的http.Server处理程序。

huangapple go评论106阅读模式
英文:

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(),

  1. const webPort = "80"
  2. type Config struct {}
  3. func main() {
  4. app := Config{}
  5. log.Printf("Starting broker service on port %s\n",webPort)
  6. srv := &http.Server{
  7. Addr: fmt.Sprintf(":%s",webPort),
  8. Handler:app.routes(),
  9. }
  10. err := srv.ListenAndServe()
  11. if(err != nil) {
  12. log.Panic(err)
  13. }
  14. }

and in routes file :

  1. func (app *Config) routes() http.Handler {
  2. mux := chi.NewRouter()
  3. mux.Use(cors.Handler(cors.Options{
  4. AllowedOrigins: []string{"http://*","https://*"},
  5. AllowedMethods: []string{"GET", "POST", "DELETE","PUT","OPTIONS"},
  6. AllowedHeaders: []string{"Accept","Authorization","Content-Type","X-CSRF-Token"},
  7. ExposedHeaders: []string{"Link"},
  8. AllowCredentials:true,
  9. MaxAge:300,
  10. }))
  11. mux.Use(middleware.Heartbeat("/ping"))
  12. mux.Post("/",app.Broker)
  13. return mux
  14. }

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

  1. app := Config{}

from where does app knows about routes() ?

what is the :
func (app *Config)
in the function ?

答案1

得分: 3

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

  1. srv := &http.Server{
  2. Addr: ":8081", // 端口
  3. Handler: app.routes() // 调用的处理程序
  4. }

routesConfig 结构体的一个方法。即使 Config 是空的,我们仍然可以像你的代码中一样调用 routes 方法。

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

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

英文:

Routes have been attached to the HTTP server as shown below.

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

routes is a method of Config struct. We can still call the routes methods as in your code even when Config is empty.

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

Config struct is acting as a method receiver here.

huangapple
  • 本文由 发表于 2023年3月17日 17:31:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75765867.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定