Home > Net >  Stop Echo server on api call in golang
Stop Echo server on api call in golang

Time:08-05

I am new to Golang and Echo framework. I have started a server using code as shown below and want to stop the server on an API hit which is /stopServer. Google making me more confused as I am not able to find this on the API hit. All I am able to see is stopping server on terminal interrupt. Any pointers would be appreciable.

func stopServer(c echo.Context) error {
    //Some code which I am not sure about
}

func main() {
    // Echo instance
    e := echo.New()

    e.GET("/stopServer", stopServer)

    // Start server
    e.Logger.Fatal(e.Start(":1323"))
}

I would also like to print the message on http://localhost:1323/stopServer saying "Server stopped successfully"

CodePudding user response:

You can follow the Graceful Shutdown Recipe source code.

echo Graceful Shutdown Recipe

more option

and refer following code snippet

package main
import (
    "context"
    "github.com/labstack/echo/v4"
    "net/http"
)
func stopServer(c echo.Context) error {
    err := c.Echo().Shutdown(context.Background())
    if err != nil {
        if err != http.ErrServerClosed {
            c.Echo().Logger.Fatal("shutting down the server")
        }
}
    return nil
}
func main() {
    e := echo.New()
    e.GET("/stopServer", stopServer)
    e.Logger.Fatal(e.Start(":1323"))
}

However this will immediately shutdown the echo server and "ERR_CONNECTION_REFUSED" returned to the client.

  • Related