74 lines
1.5 KiB
Go
74 lines
1.5 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"git.systemact.nl/henk/mars-terraform-registry/internal/config"
|
|
)
|
|
|
|
type Server struct {
|
|
httpServer *http.Server
|
|
cfg *config.Config
|
|
}
|
|
|
|
func NewServer(cfg *config.Config) (*Server, error) {
|
|
srv := &Server{
|
|
cfg: cfg,
|
|
}
|
|
err := srv.setup()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("setting up server: %w", err)
|
|
}
|
|
return srv, err
|
|
}
|
|
|
|
func (s *Server) setup() error {
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("/health", s.handleHealth)
|
|
s.httpServer = &http.Server{
|
|
Addr: s.cfg.Server.BindAddress,
|
|
Handler: mux,
|
|
ReadTimeout: s.cfg.Server.ReadTimeout,
|
|
WriteTimeout: s.cfg.Server.WriteTimeout,
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) Run(ctx context.Context) error {
|
|
slog.Info("Starting Mars Terraform Registry", "address", s.cfg.Server.BindAddress)
|
|
|
|
errCh := make(chan error, 1)
|
|
go func() {
|
|
if s.cfg.TLS.Enabled {
|
|
errCh <- s.httpServer.ListenAndServeTLS(s.cfg.TLS.CertFile, s.cfg.TLS.KeyFile)
|
|
} else {
|
|
errCh <- s.httpServer.ListenAndServe()
|
|
}
|
|
}()
|
|
|
|
select {
|
|
case <-ctx.Done():
|
|
slog.Info("Shutdown signal received")
|
|
return s.Shutdown(context.Background())
|
|
case err := <-errCh:
|
|
return err
|
|
}
|
|
}
|
|
|
|
func (s *Server) Shutdown(ctx context.Context) error {
|
|
var errs []error
|
|
|
|
if err := s.httpServer.Shutdown(ctx); err != nil {
|
|
errs = append(errs, fmt.Errorf("http server shutdown: %w", err))
|
|
}
|
|
|
|
if len(errs) > 0 {
|
|
return fmt.Errorf("shutdown errors: %v", errs)
|
|
}
|
|
return nil
|
|
}
|