all repos — weimar @ b26a020c4b21a1c0d9a62bc6afdf405ea2097d82

Unnamed repository; edit this file 'description' to name the repository.

internal/server/server.go (view raw)

  1package server
  2
  3import (
  4	"context"
  5	"io/fs"
  6	"net/http"
  7	"strings"
  8
  9	"github.com/mjensen/weimar/internal/api"
 10	"github.com/mjensen/weimar/internal/auth"
 11	"github.com/mjensen/weimar/internal/config"
 12	"github.com/mjensen/weimar/internal/db"
 13	"github.com/mjensen/weimar/internal/storage"
 14)
 15
 16func New(cfg config.Config, webFS fs.FS, database *db.DB) (*Server, error) {
 17	sm := auth.NewSessionManager(database)
 18	st, err := storage.New(cfg.Storage.Path)
 19	if err != nil {
 20		return nil, err
 21	}
 22	h := api.New(database, sm, st, cfg)
 23
 24	// Load the default favicon from the embedded web build.
 25	api.InitDefaultFavicon(webFS)
 26
 27	mux := http.NewServeMux()
 28
 29	// Health check (public).
 30	mux.HandleFunc("GET /api/health", handleHealth)
 31
 32	// Public config.
 33	mux.HandleFunc("GET /api/config", h.HandleConfig)
 34
 35	// Favicon and logo (public).
 36	mux.HandleFunc("GET /favicon", h.HandleFavicon)
 37	mux.HandleFunc("GET /logo", h.HandleLogo)
 38
 39	s := &Server{
 40		cfg:  cfg,
 41		mux:  mux,
 42		auth: sm,
 43	}
 44
 45	// Auth (public).
 46	mux.HandleFunc("POST /api/auth/login", h.HandleLogin)
 47	mux.HandleFunc("POST /api/auth/register", h.HandleRegister)
 48
 49	// Auth (authenticated).
 50	mux.HandleFunc("POST /api/auth/logout", s.requireAuth(h.HandleLogout))
 51
 52	// Images (conditionally public).
 53	mux.HandleFunc("POST /api/upload", s.requireAuth(h.HandleUpload))
 54	mux.HandleFunc("GET /api/images", s.requireAuthOrPublic(h.HandleListImages))
 55	mux.HandleFunc("GET /api/images/{id}", s.requireAuthOrPublic(h.HandleGetImage))
 56	mux.HandleFunc("GET /api/images/{id}/download", s.requireAuthOrPublic(h.HandleDownload))
 57	mux.HandleFunc("GET /api/images/{id}/thumbnail", s.requireAuthOrPublic(h.HandleThumbnail))
 58	mux.HandleFunc("POST /api/images/{id}/tags", s.requireAuth(h.HandleAddTags))
 59	mux.HandleFunc("DELETE /api/images/{id}/tags", s.requireAuth(h.HandleRemoveTags))
 60
 61	// Tags (authenticated).
 62	mux.HandleFunc("GET /api/tags/suggest", s.requireAuth(h.HandleTagSuggest))
 63
 64	// Users (authenticated).
 65	mux.HandleFunc("GET /api/users/me", s.requireAuth(h.HandleGetMe))
 66	mux.HandleFunc("POST /api/users/me/avatar", s.requireAuth(h.HandleUploadAvatar))
 67	mux.HandleFunc("GET /api/users/{id}/avatar", h.HandleServeAvatar)
 68
 69	// SPA — serve index.html for all non-API routes (client-side routing).
 70	mux.Handle("/", s.spaHandler(webFS))
 71
 72	return s, nil
 73}
 74
 75type Server struct {
 76	cfg  config.Config
 77	mux  *http.ServeMux
 78	auth *auth.SessionManager
 79}
 80
 81func (s *Server) Start(ctx context.Context) error {
 82	addr := s.cfg.Server.Host + ":" + itoa(s.cfg.Server.Port)
 83
 84	// Wrap the mux with a handler that sets security headers.
 85	handler := securityHeaders(s.mux)
 86
 87	srv := &http.Server{Addr: addr, Handler: handler}
 88
 89	go func() {
 90		<-ctx.Done()
 91		srv.Shutdown(context.Background())
 92	}()
 93
 94	return srv.ListenAndServe()
 95}
 96
 97func itoa(n int) string {
 98	if n == 0 {
 99		return "0"
100	}
101	var buf [20]byte
102	i := len(buf)
103	for n > 0 {
104		i--
105		buf[i] = byte('0' + n%10)
106		n /= 10
107	}
108	return string(buf[i:])
109}
110
111// spaHandler serves static files for SPA client-side routing.
112// For routes that don't match an existing file (e.g. /browse, /image/123),
113// it falls back to serving index.html so the SPA router can handle them.
114func (s *Server) spaHandler(webFS fs.FS) http.HandlerFunc {
115	fsHandler := http.FileServer(http.FS(webFS))
116	return func(w http.ResponseWriter, r *http.Request) {
117		// API routes should not be served by the SPA handler.
118		if strings.HasPrefix(r.URL.Path, "/api/") {
119			http.NotFound(w, r)
120			return
121		}
122
123		// Check if the requested file exists in the embedded FS.
124		path := strings.TrimPrefix(r.URL.Path, "/")
125		if _, err := fs.Stat(webFS, path); err != nil {
126			// File doesn't exist — serve index.html for SPA routing.
127			r.URL.Path = "/"
128			fsHandler.ServeHTTP(w, r)
129			return
130		}
131
132		// File exists — serve it directly.
133		fsHandler.ServeHTTP(w, r)
134	}
135}
136
137func handleHealth(w http.ResponseWriter, r *http.Request) {
138	w.Header().Set("Content-Type", "application/json")
139	w.Write([]byte(`{"status":"ok"}`))
140}
141
142// securityHeaders wraps a handler with security-related HTTP headers.
143func securityHeaders(next http.Handler) http.Handler {
144	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
145		w.Header().Set("X-Content-Type-Options", "nosniff")
146		w.Header().Set("X-Frame-Options", "DENY")
147		w.Header().Set("Referrer-Policy", "same-origin")
148		next.ServeHTTP(w, r)
149	})
150}