How do I be able to stop and start the server by calling defined functions.
import (
"context"
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
)
var server *http.Server
var appCtx context.Context
func main() {
server = createHTTPServer(":8080")
ctx = appCtx
startServer(ctx)
time.Sleep(10*time.Second)
stopServer()
time.Sleep(10*time.Second)
startServer(ctx) // SERVER cannot start again err.ErrServerClosed!!!
}
//=======================================//
func startServer(ctx) error {
errs, _ := errgroup.WithContext(ctx)
errs.Go(func() error {
if err := server.ListenAndServe(); err != nil {
return fmt.Errorf(err.Error())
}
return nil
})
return errs.Wait()
}
func stopServer() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := a.server.Shutdown(ctx); err != nil {
fmt.Println(err)
}
return nil
}
func createHTTPServer(addr string) (server *http.Server) {
router := gin.Default()
router.GET("/", func(gCon *gin.Context) {
gCon.JSON(http.StatusOK, gin.H{"code": http.StatusOK, "data": "", "msg": "Welcome to the GoLang HTTP Server!"})
})
server = &http.Server{
Addr: addr,
Handler: router,
}
return server
}
Environments Go Version: go1.17.6 Platform: windows Architecture: amd64 Gin Version: v1.7.7
Comment From: KiddoV
Never mind! I got it working.
func stopServer() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := a.server.Shutdown(ctx); err != nil {
fmt.Println(err)
}
server = createHTTPServer(":8080") //Re-create server instance again after stopping the server
return nil
}