Home >Backend Development >Golang >Golang and Gin Web Framework - Execute code after router.Run()
php Editor Banana brings you exciting content about Golang and Gin Web framework. When writing web applications using Gin, we often need to execute some code after router.Run(). These codes may include database connection, cache initialization and other operations. This article will introduce in detail how to implement the method of executing code after router.Run() in the Gin framework, helping you better master the usage skills of the Gin framework.
I'm pretty new to go, so please excuse me if this is something obvious.
I'm busy writing some code for oauth 2.0 authentication in go. Part of this means I need to have a callback url available. In my code I need to create a callback endpoint and once it's up and running I need to call an authorization endpoint which will then connect to my callback endpoint.
My problem is that calling run() in gin blocks my execution so I can't do any further authorization after the callback endpoint is up and running. Is there a way to run this code in a separate goroutine so that I can then complete the authorization flow?
Here is a rough example of the code in my main function:
r := gin.Default() //ReqHandler is an HtttpHandler func r.GET("/redirect", ReqHandler) r.Run(":5001") ContinueAuth()
Create a listener in the main goroutine. Start http server in goroutine. Continue the authentication flow in the main goroutine.
r := gin.Default() r.GET("/redirect", ReqHandler) l, err := net.Listen("tcp", ":5001") if err != nil { log.Fatal(err) } go func() { log.Fatal(r.RunListener(l)) }() ContinueAuth() select {} // wait forever
Creating the listener in the main goroutine ensures that the listener is ready to call back from the authentication flow.
The above is the detailed content of Golang and Gin Web Framework - Execute code after router.Run(). For more information, please follow other related articles on the PHP Chinese website!