Home > Back-end >  How to stop and start gin server multiple times in one run
How to stop and start gin server multiple times in one run

Time:09-01

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.

CodePudding user response:

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()))
    }
    {
        srv := serve()

        time.Sleep(time.Second * 3)

        fmt.Println("up", srv.ListenAndServe())
    }

    select {}
}


CodePudding user response:

I tried many ways and finally wrote an article as a result, this will help you to solve the problem: https://dev.to/arshamalh/trying-to-shutdown-a-gin-server-goroutines-and-channels-tips-gf3

  • Related