legalgo-BE-go/internal/config/chi_router.go
2025-02-24 16:48:20 +08:00

52 lines
987 B
Go

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("/api", 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")
}
}