gin webframework using reuseport listener

Using SO_REUSEPORT with the Gin framework in Go involves setting up the HTTP server with custom socket options. Here’s an example of how you can use SO_REUSEPORT with Gin:

Step 1: Install go-netreuse

First, we need the go-netreuse package to enable the SO_REUSEPORT option.

 
go get github.com/libp2p/go-reuseport

Step 2: Set up the Gin server with SO_REUSEPORT

Here’s the code to start a Gin server using SO_REUSEPORT to allow multiple processes to bind to the same port:

package main

import (
    "log"
    "net"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"

    reuseport "github.com/libp2p/go-reuseport"
    "github.com/gin-gonic/gin"
)

func main() {
    // Create a new Gin router
    r := gin.Default()

    // Set up a sample route
    r.GET("/", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "Hello, World!",
        })
    })

    // Create a listener with SO_REUSEPORT enabled
    listener, err := reuseport.Listen("tcp", ":8080")
    if err != nil {
        log.Fatalf("Failed to listen on port 8080: %v", err)
    }
    defer listener.Close()

    // Set up server
    srv := &http.Server{
        Handler:      r,
        ReadTimeout:  10 * time.Second,
        WriteTimeout: 10 * time.Second,
        IdleTimeout:  30 * time.Second,
    }

    // Listen for system interrupts and gracefully shutdown the server
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

    go func() {
        if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
            log.Fatalf("Server error: %v", err)
        }
    }()
    log.Println("Server is running on port 8080...")

    <-quit
    log.Println("Shutting down server...")

    if err := srv.Shutdown(nil); err != nil {
        log.Fatalf("Server forced to shutdown: %v", err)
    }

    log.Println("Server exited")
}

Explanation

  • reuseport.Listen: We use this function from go-reuseport to create a listener that enables the SO_REUSEPORT socket option.
  • Graceful Shutdown: Using os/signal to handle system interrupts and gracefully shutdown the server.
  • Listener Close: When the server exits, it closes the listener to release the port.

Running Multiple Instances

You can run multiple instances of this server, and they will all bind to the same port 8080 due to the SO_REUSEPORT option. This approach is commonly used for load balancing across multiple server instances without an external load balancer.

 

分类: 编程语言 标签: gin SO_REUSEPORT listener net.Listener reuseport.Listen 发布于: 2024-11-03 11:13:26, 点击数: