gofibers

How to stop and start gin server multiple times in one run


I'm writing a program that I need to Start and Stop my server (using Gin framework in this case) multiple times when my program is running,

Stopping a gin server itself needed a trick that I found in this question: Graceful stop of gin server

But this kind of approach will prevent my program to start the gin server in the future, according to the documentation of http.Server.Shutdown() method that says:

Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Serve will return ErrServerClosed.

I exactly need that future calls.

Aditional Information

Fiber can handle this situation so easily, but I want to make it with gin.

I want something like this fiber code:

  fiber := NewFiberApp()
  fiber.RegisterRoutes()
  fiber.Start() // Calls fiber.Listen() Under the hood
  fiber.Stop() // Calls fiber.Shutdown() Under the hood
  fiber.Start()
  fiber.Stop()
  fiber.Start()

And it works as I expect.


Solution

  • You need to create the server struct from scratch!

    Can't use the closed http.Server again.

    
    func serve() *http.Server {
        router := gin.Default()
        router.GET("/", func(c *gin.Context) {
            time.Sleep(5 * time.Second)
            c.String(http.StatusOK, "Welcome Gin Server\n")
        })
    
        srv := &http.Server{
            Addr:    ":8080",
            Handler: router,
        }
    
        go func() {
            // service connections
            if err := srv.ListenAndServe(); err != nil {
                log.Printf("listen: %s\n", err)
            }
        }()
    
        return srv
    }
    
    func main() {
        {
            srv := serve()
    
            time.Sleep(time.Second * 3)
    
            fmt.Println("down", srv.Shutdown(context.Background()))
        }
        {
            time.Sleep(time.Second * 3)
    
            fmt.Println("up", serve())
        }
    
        select {}
    }