service/library/httpserver/httpserver.go

43 lines
842 B
Go

package httpserver
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"service/library/configcenter"
"syscall"
"time"
"service/library/logger"
)
func StartHttpServer(srv *http.Server, cfg *configcenter.DefaultConfig) {
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Fatal("listen: %v", err)
}
}()
logger.Info("Server %s start at %s", cfg.App.AppName, srv.Addr)
quit := make(chan os.Signal)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
logger.Info("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
select {
case <-ctx.Done():
logger.Info("timeout of 1 seconds.")
}
logger.Info("Server exited")
}