http.go

 1package web
 2
 3import (
 4	"context"
 5	"net/http"
 6	"time"
 7
 8	"github.com/charmbracelet/log/v2"
 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
17	Server *http.Server
18}
19
20// NewHTTPServer creates a new HTTP server.
21func NewHTTPServer(ctx context.Context) (*HTTPServer, error) {
22	cfg := config.FromContext(ctx)
23	logger := log.FromContext(ctx)
24	s := &HTTPServer{
25		ctx: ctx,
26		cfg: cfg,
27		Server: &http.Server{
28			Addr:              cfg.HTTP.ListenAddr,
29			Handler:           NewRouter(ctx),
30			ReadHeaderTimeout: time.Second * 10,
31			IdleTimeout:       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() //nolint:wrapcheck
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) //nolint:wrapcheck
49	}
50	return s.Server.ListenAndServe() //nolint:wrapcheck
51}
52
53// Shutdown gracefully shuts down the HTTP server.
54func (s *HTTPServer) Shutdown(ctx context.Context) error {
55	return s.Server.Shutdown(ctx) //nolint:wrapcheck
56}