2024-04-07 12:11:25 +07:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2024-04-07 16:06:33 +07:00
|
|
|
"context"
|
|
|
|
"errors"
|
2024-04-07 12:11:25 +07:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"github.com/tigorlazuardi/redmage/config"
|
2024-04-07 16:06:33 +07:00
|
|
|
"github.com/tigorlazuardi/redmage/pkg/caller"
|
|
|
|
"github.com/tigorlazuardi/redmage/pkg/errs"
|
|
|
|
"github.com/tigorlazuardi/redmage/pkg/log"
|
2024-04-07 12:11:25 +07:00
|
|
|
"github.com/tigorlazuardi/redmage/server/routes/api"
|
2024-04-07 23:41:00 +07:00
|
|
|
"github.com/tigorlazuardi/redmage/server/routes/www"
|
2024-04-07 12:11:25 +07:00
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
2024-04-07 16:06:33 +07:00
|
|
|
server *http.Server
|
|
|
|
config *config.Config
|
2024-04-07 12:11:25 +07:00
|
|
|
}
|
|
|
|
|
2024-04-07 16:06:33 +07:00
|
|
|
func (srv *Server) Start(exit <-chan struct{}) error {
|
|
|
|
errch := make(chan error, 1)
|
|
|
|
caller := caller.New(3)
|
|
|
|
go func() {
|
2024-04-08 15:48:45 +07:00
|
|
|
log.New(context.Background()).Caller(caller).Info("starting http server", "address", "http://"+srv.server.Addr)
|
2024-04-07 16:06:33 +07:00
|
|
|
errch <- srv.server.ListenAndServe()
|
|
|
|
}()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-exit:
|
2024-04-08 15:48:45 +07:00
|
|
|
log.New(context.Background()).Caller(caller).Info("received exit signal. shutting down server")
|
2024-04-07 16:06:33 +07:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), srv.config.Duration("http.shutdown_timeout"))
|
|
|
|
defer cancel()
|
|
|
|
return srv.server.Shutdown(ctx)
|
|
|
|
case err := <-errch:
|
|
|
|
if errors.Is(err, http.ErrServerClosed) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return errs.Wrap(err)
|
|
|
|
}
|
2024-04-07 12:11:25 +07:00
|
|
|
}
|
|
|
|
|
2024-04-07 23:41:00 +07:00
|
|
|
func New(cfg *config.Config, api *api.API, www *www.WWW) *Server {
|
2024-04-07 12:11:25 +07:00
|
|
|
router := chi.NewRouter()
|
|
|
|
|
|
|
|
router.Route("/api", api.Register)
|
2024-04-07 23:41:00 +07:00
|
|
|
router.Route("/", www.Register)
|
2024-04-07 12:11:25 +07:00
|
|
|
|
2024-04-07 16:06:33 +07:00
|
|
|
server := &http.Server{
|
|
|
|
Handler: router,
|
|
|
|
Addr: cfg.String("http.host") + ":" + cfg.String("http.port"),
|
2024-04-07 12:11:25 +07:00
|
|
|
}
|
2024-04-07 16:06:33 +07:00
|
|
|
|
|
|
|
return &Server{server: server, config: cfg}
|
2024-04-07 12:11:25 +07:00
|
|
|
}
|