everybody loves a refactor

This commit is contained in:
2026-02-15 12:27:36 +11:00
parent 2944443143
commit c5f6fe6098
44 changed files with 278 additions and 234 deletions

36
internal/respond/error.go Normal file
View File

@@ -0,0 +1,36 @@
// Package respond provides utilities for raw HTTP responses that don't fit into the throw or notify categories
package respond
import (
"encoding/json"
"fmt"
"net/http"
)
func OK(w http.ResponseWriter) {
w.WriteHeader(http.StatusOK)
}
func BadRequest(w http.ResponseWriter, err error) {
respondError(w, http.StatusBadRequest, err)
}
func NotFound(w http.ResponseWriter, err error) {
respondError(w, http.StatusNotFound, err)
}
func Conflict(w http.ResponseWriter, err error) {
respondError(w, http.StatusConflict, err)
}
func respondError(w http.ResponseWriter, statusCode int, err error) {
details := map[string]any{
"error": statusCode,
"details": fmt.Sprintf("%s", err),
}
resp, err := json.Marshal(details)
w.WriteHeader(statusCode)
if err == nil {
_, _ = w.Write(resp)
}
}

View File

@@ -0,0 +1,39 @@
package respond
import (
"fmt"
"net/http"
"path/filepath"
)
func HXRedirect(w http.ResponseWriter, format string, a ...any) {
w.Header().Set("HX-Redirect", fmt.Sprintf(format, a...))
w.WriteHeader(http.StatusOK)
}
func ContentType(w http.ResponseWriter, r *http.Request) {
ext := filepath.Ext(r.URL.Path)
if contentType := mimeTypes[ext]; contentType != "" {
w.Header().Set("Content-Type", contentType)
}
}
// Common MIME types for static files
var mimeTypes = map[string]string{
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".xml": "application/xml; charset=utf-8",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".webp": "image/webp",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".eot": "application/vnd.ms-fontobject",
}