feat: initial router on main function

This commit is contained in:
ericprd
2025-02-22 16:15:38 +08:00
parent e57fa3ac6c
commit 3dd84e6932
9 changed files with 150 additions and 55 deletions
+51
View File
@@ -0,0 +1,51 @@
package pkgconfig
import (
"context"
"fmt"
"net/http"
"os/signal"
"syscall"
"time"
"github.com/go-chi/chi/v5"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
)
func Router(apiRouter chi.Router) {
mainRouter := chi.NewRouter()
mainRouter.Mount("/", apiRouter)
mainCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
svr := &http.Server{
Addr: fmt.Sprintf(":%d", APP_PORT),
Handler: mainRouter,
}
group, groupCtx := errgroup.WithContext(mainCtx)
group.Go(func() error {
logrus.Infof("Listening to port %d", APP_PORT)
return svr.ListenAndServe()
})
group.Go(func() error {
<-groupCtx.Done()
ctxTimeout, cancel := context.WithTimeout(mainCtx, GRACEFULL_TIMEOUT*time.Second)
defer cancel()
svr.Shutdown(ctxTimeout)
return nil
})
if err := group.Wait(); err != nil {
logrus.Errorf("system exit, reason: %v", err.Error())
} else {
logrus.Info("system exit normally")
}
}
+4
View File
@@ -0,0 +1,4 @@
package pkgconfig
const APP_PORT = 3000
const GRACEFULL_TIMEOUT = 20