1package web
 2
 3import (
 4	"context"
 5	"net/http"
 6	"time"
 7
 8	"github.com/charmbracelet/log"
 9	"github.com/charmbracelet/soft-serve/pkg/config"
10)
11
12// HTTPServer is an http server.
13type HTTPServer struct {
14	ctx    context.Context
15	cfg    *config.Config
16	server *http.Server
17}
18
19// NewHTTPServer creates a new HTTP server.
20func NewHTTPServer(ctx context.Context) (*HTTPServer, error) {
21	cfg := config.FromContext(ctx)
22	logger := log.FromContext(ctx).WithPrefix("http")
23	s := &HTTPServer{
24		ctx: ctx,
25		cfg: cfg,
26		server: &http.Server{
27			Addr:              cfg.HTTP.ListenAddr,
28			Handler:           NewRouter(ctx),
29			ReadHeaderTimeout: time.Second * 10,
30			ReadTimeout:       time.Second * 10,
31			WriteTimeout:      time.Second * 10,
32			MaxHeaderBytes:    http.DefaultMaxHeaderBytes,
33			ErrorLog:          logger.StandardLog(log.StandardLogOptions{ForceLevel: log.ErrorLevel}),
34		},
35	}
36
37	return s, nil
38}
39
40// Close closes the HTTP server.
41func (s *HTTPServer) Close() error {
42	return s.server.Close()
43}
44
45// ListenAndServe starts the HTTP server.
46func (s *HTTPServer) ListenAndServe() error {
47	if s.cfg.HTTP.TLSKeyPath != "" && s.cfg.HTTP.TLSCertPath != "" {
48		return s.server.ListenAndServeTLS(s.cfg.HTTP.TLSCertPath, s.cfg.HTTP.TLSKeyPath)
49	}
50	return s.server.ListenAndServe()
51}
52
53// Shutdown gracefully shuts down the HTTP server.
54func (s *HTTPServer) Shutdown(ctx context.Context) error {
55	return s.server.Shutdown(ctx)
56}