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