Running server in goroutine?

王林
Release: 2024-02-11 08:30:08
forward
434 people have browsed it

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

In the main function, I only call the Start() function.

server.Start()
Copy after login

Is this okay? Or should I do this in a goroutine like this:

go func(){
   server.Start()
}()
Copy after login
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!

Related labels:
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