Home  >  Article  >  Backend Development  >  Running server in goroutine?

Running server in goroutine?

王林
王林forward
2024-02-11 08:30:08388browse

在 goroutine 中运行服务器?

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.

Question content

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()
}()
A lot of other stuff happens in

main.go - queue listeners are initialized, databases etc.

Workaround

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete