Spaces:
Building
Building
package app | |
import ( | |
"context" | |
"errors" | |
"github.com/gin-gonic/gin" | |
"kpl/pkg/logx" | |
"net/http" | |
"time" | |
) | |
func Start(ctx context.Context) func(ctx context.Context) { | |
gin.SetMode(gin.ReleaseMode) | |
e := gin.New() | |
e.Use(gin.Recovery()) | |
e.GET("/", func(ctx *gin.Context) { | |
ctx.String(http.StatusOK, "Hello World!") | |
}) | |
srv := &http.Server{ | |
Addr: ":3040", | |
Handler: e, | |
} | |
go func() { | |
logx.WithContext(ctx).Infof("http server initialized successfully at \u001B[35m%v\u001B[0m", srv.Addr) | |
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { | |
panic(err) | |
} | |
}() | |
return func(ctx context.Context) { | |
logx.WithContext(ctx).Info("http server shutdown.") | |
ctx, cancel := context.WithTimeout(ctx, time.Second*5) | |
srv.SetKeepAlivesEnabled(false) | |
if err := srv.Shutdown(ctx); err != nil { | |
logx.WithContext(ctx).Error(err.Error()) | |
} | |
cancel() | |
} | |
} | |