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

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

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() // 调用的处理程序
}

routesConfig 结构体的一个方法。即使 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.

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:

确定