Search code examples
gogo-gin

Golang and Gin web framework - Execute code after router.Run()


I am fairly new to Go, so please excuse me if this is something obvious.

I am busy writing some code in Go for OAuth 2.0 Authentication. Part of this means that I need to have a callback URL available. In my code I need to create a callback endpoint, and once this is up and running I need to call an Authorization endpoint which will then reach out to my callback endpoint.

My problem being that calling Run() in Gin is blocking my execution, so I can't do any further authorization after my callback endpoint is up and running. Is there a way to maybe run this code in a separate GoRoutine so that I can finish my Authorization flow afterwards?

Here is a rough example of my code in my main function:

r := gin.Default()
//ReqHandler is an HtttpHandler func
r.GET("/redirect", ReqHandler)

r.Run(":5001")
ContinueAuth()

Solution

  • Create a listener in the main goroutine. Start the HTTP server in a goroutine. Continue with auth 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 for callbacks from the authentication flow.