php editor Apple will discuss a question in this article: "Running the server in goroutine?" Goroutine is a lightweight concurrency mechanism in the Go language that can create data in the program. Thousands of concurrent execution units. But is it possible to run the server in a goroutine? The answer to this question is not simple and there are several factors to consider. In the following content, we will explore this problem and give some solutions.
I have a Golang service that is listening for Kafka messages, but I also want to start an http server in it for health checks. The server code is simple:
package server import ( "net/http" "github.com/gin-gonic/gin" ) func Start() { port := ":8080" r := setupRouter() r.Run(port) } func setupRouter() *gin.Engine { r := gin.Default() r.GET("/health", func(ctx *gin.Context) { ctx.JSON(http.StatusOK, gin.H{"status": "OK"}) }) return r }
In the main function, I only call the Start() function.
server.Start()
Is this okay? Or should I do this in a goroutine like this:
go func(){ server.Start() }()
main.go - queue listeners are initialized, databases etc.
If you don't want Run
to block your main thread, you will need a go routine.
go server.Start()
The above is the detailed content of Running server in goroutine?. For more information, please follow other related articles on the PHP Chinese website!