Parent directory

server.go

1103 bytes
 1package web
 2
 3import (
 4	"context"
 5	"net/http"
 6
 7	"charm.land/log/v2"
 8	"github.com/charmbracelet/soft-serve/pkg/config"
 9	"github.com/charmbracelet/soft-serve/pkg/web/pages"
10	"github.com/gorilla/handlers"
11	"github.com/gorilla/mux"
12)
13
14// NewRouter returns a new HTTP router.
15func NewRouter(ctx context.Context) http.Handler {
16	logger := log.FromContext(ctx).WithPrefix("http")
17	router := mux.NewRouter()
18
19	// Health routes
20	HealthController(ctx, router)
21
22	// Go import metadata routes
23	GoGetController(ctx, router)
24
25	// Git and LFS routes
26	GitController(ctx, router)
27
28	if config.FromContext(ctx).HTTP.WebUI.Enabled {
29		pages.Controller(ctx, router)
30	}
31
32	router.PathPrefix("/").HandlerFunc(renderNotFound)
33
34	// Context handler
35	// Adds context to the request
36	h := NewLoggingMiddleware(router, logger)
37	h = NewContextHandler(ctx)(h)
38	h = handlers.RecoveryHandler()(h)
39
40	cfg := config.FromContext(ctx)
41
42	h = handlers.CORS(handlers.AllowedHeaders(cfg.HTTP.CORS.AllowedHeaders),
43		handlers.AllowedOrigins(cfg.HTTP.CORS.AllowedOrigins),
44		handlers.AllowedMethods(cfg.HTTP.CORS.AllowedMethods),
45	)(h)
46
47	return h
48}