pkg/web/web.go 2.9 K raw
1
// Package web provides shared HTTP helpers used across andromeda Go apps.
2
package web
3
4
import (
5
	"embed"
6
	"encoding/json"
7
	"html/template"
8
	"log/slog"
9
	"mime"
10
	"net/http"
11
	"net/url"
12
	"path/filepath"
13
	"strconv"
14
	"strings"
15
)
16
17
// EmbeddedHandler serves files from an embed.FS under the given URL prefix.
18
// Files are looked up relative to the same prefix inside the embedded FS.
19
func EmbeddedHandler(fs embed.FS, prefix string) http.HandlerFunc {
20
	return func(w http.ResponseWriter, r *http.Request) {
21
		name := strings.TrimPrefix(r.URL.Path, "/"+prefix+"/")
22
		path := filepath.ToSlash(filepath.Join(prefix, name))
23
		data, err := fs.ReadFile(path)
24
		if err != nil {
25
			http.NotFound(w, r)
26
			return
27
		}
28
		if ct := mime.TypeByExtension(filepath.Ext(path)); ct != "" {
29
			w.Header().Set("Content-Type", ct)
30
		}
31
		_, _ = w.Write(data)
32
	}
33
}
34
35
// Render executes a named template into w with status 200. Errors are logged
36
// and surfaced as HTTP 500.
37
func Render(t *template.Template, w http.ResponseWriter, name string, data any, log *slog.Logger) {
38
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
39
	if err := t.ExecuteTemplate(w, name, data); err != nil {
40
		if log != nil {
41
			log.Error("template render failed", "name", name, "err", err)
42
		}
43
		http.Error(w, "template error", http.StatusInternalServerError)
44
	}
45
}
46
47
// WriteJSON writes data as JSON with the given status code.
48
func WriteJSON(w http.ResponseWriter, status int, data any) {
49
	w.Header().Set("Content-Type", "application/json")
50
	w.WriteHeader(status)
51
	_ = json.NewEncoder(w).Encode(data)
52
}
53
54
// DecodeJSON decodes r.Body into dst. On failure it writes a 400 JSON error
55
// and returns false.
56
func DecodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
57
	defer r.Body.Close()
58
	if err := json.NewDecoder(r.Body).Decode(dst); err != nil {
59
		WriteError(w, http.StatusBadRequest, "invalid JSON")
60
		return false
61
	}
62
	return true
63
}
64
65
// WriteError writes a JSON error response of the form {"error": msg} with the
66
// given status code.
67
func WriteError(w http.ResponseWriter, status int, msg string) {
68
	WriteJSON(w, status, map[string]any{"error": msg})
69
}
70
71
// PathInt64 parses a positive int64 path value from r. Returns (0, false) if
72
// missing, unparseable, or non-positive.
73
func PathInt64(r *http.Request, name string) (int64, bool) {
74
	id, err := strconv.ParseInt(r.PathValue(name), 10, 64)
75
	if err != nil || id <= 0 {
76
		return 0, false
77
	}
78
	return id, true
79
}
80
81
// RedirectWithError issues a 303 redirect to target with ?error=msg appended.
82
func RedirectWithError(w http.ResponseWriter, r *http.Request, target, msg string) {
83
	http.Redirect(w, r, target+"?error="+url.QueryEscape(msg), http.StatusSeeOther)
84
}
85
86
// RedirectWithSuccess issues a 303 redirect to target with ?success=msg appended.
87
func RedirectWithSuccess(w http.ResponseWriter, r *http.Request, target, msg string) {
88
	http.Redirect(w, r, target+"?success="+url.QueryEscape(msg), http.StatusSeeOther)
89
}