Home  >  Article  >  Backend Development  >  How to properly shut down the Gin service in Go

How to properly shut down the Gin service in Go

PHPz
PHPzOriginal
2023-04-11 09:14:571468browse

When developing using the Go language web development framework Gin, sometimes it is necessary to manually close the Gin service to release port resources or perform other operations. This article will explain how to shut down the Gin service correctly.

Gin's default startup method

When using Gin, we usually use the following code to start an http service:

router := gin.Default()

router.GET("/", func(c *gin.Context) {
    c.String(http.StatusOK, "Hello, Gin!")
})

router.Run(":8080")

This example code starts the default Gin router, Handles GET requests for / paths and returns a string. Finally, the Run method is called to start the Gin service and listen to port 8080.

It should be noted that the Run method is a blocking call that always occupies the main thread so that it can continuously monitor the port and process requests and responses. Therefore, when we need to manually shut down the Gin service, we need to use a non-blocking method to start it.

Use http.Server Start Gin

In order to manually shut down the Gin service, we need to use Go's built-in http.Server, which provides A Shutdown method that can shut down the http service gracefully.

We need to follow the following steps to use http.Server to start Gin:

  1. Create a http.Server instance and set up a listener Address and Gin router as processor:
s := &http.Server{
    Addr:    ":8080",
    Handler: router,
}
  1. Start a goroutine in which the ListenAndServe method of http.Server is called, asynchronously Start the Gin service:
go func() {
    if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        log.Fatalf("listen: %s\n", err)
    }
}()
  1. When you need to shut down the Gin service, call the Shutdown method of http.Server to ensure that it can be shut down gracefully Service:
if err := s.Shutdown(context.Background()); err != nil {
    log.Fatal("Server forced to shutdown:", err)
}

Full code example:

package main

import (
    "context"
    "log"
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()

    router.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "Hello, Gin!")
    })

    s := &http.Server{
        Addr:    ":8080",
        Handler: router,
    }

    go func() {
        if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("listen: %s\n", err)
        }
    }()

    // 假设需要在 5 秒后关闭服务
    <-time.After(5 * time.Second)
    if err := s.Shutdown(context.Background()); err != nil {
        log.Fatal("Server forced to shutdown:", err)
    }
    log.Println("Server shutdown gracefully")
}

The above code passes the Gin router as a handler to http.Server, using ListenAndServe method starts the Gin service. Then, run the http service asynchronously in a goroutine to ensure that the main thread is not blocked. Finally, wait for 5 seconds in the main thread and then call the Shutdown method to gracefully shut down the Gin service and print the log.

Summary

This article introduces how to shut down the Gin service correctly. Using Go's built-in http.Server, you can shut down the http service gracefully and avoid the possibility of sudden service interruption. Resource leakage and other problems caused.

Of course, the above code is only a sample code and is not recommended for direct use in a production environment. When referring to the code, it needs to be appropriately modified and optimized according to the actual situation and needs.

The above is the detailed content of How to properly shut down the Gin service in Go. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:How to debug golangNext article:How to debug golang