Redmage/server/server.go

58 lines
1.4 KiB
Go
Raw Normal View History

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"
"github.com/tigorlazuardi/redmage/server/routes/htmx"
)
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() {
log.Log(context.Background()).Caller(caller).Info("starting http server", "address", "http://"+srv.server.Addr)
errch <- srv.server.ListenAndServe()
}()
select {
case <-exit:
log.Log(context.Background()).Caller(caller).Info("received exit signal. shutting down server")
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
}
func New(cfg *config.Config) *Server {
router := chi.NewRouter()
router.Route("/api", api.Register)
router.Route("/htmx", htmx.Register)
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
}