Home > Backend Development > Golang > Golang and Gin Web Framework - Execute code after router.Run()

Golang and Gin Web Framework - Execute code after router.Run()

王林
Release: 2024-02-11 23:03:08
forward
999 people have browsed it

Golang 和 Gin Web 框架 - 在 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.

Question content

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()
Copy after login

Solution

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
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template