54 lines
1.0 KiB
Go
Raw Permalink Normal View History

2025-02-22 16:15:38 +08:00
package pkgconfig
import (
"context"
"fmt"
"net/http"
"os/signal"
"syscall"
"time"
"legalgo-BE-go/config"
2025-02-22 16:15:38 +08:00
"github.com/go-chi/chi/v5"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
)
func Router(apiRouter chi.Router) {
mainRouter := chi.NewRouter()
2025-02-24 16:48:20 +08:00
mainRouter.Mount("/api", apiRouter)
2025-02-22 16:15:38 +08:00
mainCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
svr := &http.Server{
Addr: fmt.Sprintf(":%d", config.APP_PORT),
2025-02-22 16:15:38 +08:00
Handler: mainRouter,
}
group, groupCtx := errgroup.WithContext(mainCtx)
group.Go(func() error {
2025-02-26 22:28:19 +08:00
logrus.Infof("Listening to port %d", config.APP_PORT)
2025-02-22 16:15:38 +08:00
return svr.ListenAndServe()
})
group.Go(func() error {
<-groupCtx.Done()
2025-02-26 22:28:19 +08:00
ctxTimeout, cancel := context.WithTimeout(mainCtx, time.Duration(config.GRACEFULL_TIMEOUT)*time.Second)
2025-02-22 16:15:38 +08:00
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")
}
}