Files
garage/backend/internal/handlers/handlers.go
T
2026-08-06 18:26:45 +12:00

126 lines
4.0 KiB
Go

// Package handlers implements the JSON API. All handlers hang off Handlers,
// which carries the shared dependencies (DB, storage, auth) they need.
package handlers
import (
"context"
"database/sql"
"encoding/json"
"net/http"
"strconv"
"strings"
"github.com/jmoiron/sqlx"
"vlog/internal/auth"
"vlog/internal/storage"
)
type Handlers struct {
DB *sqlx.DB
Storage storage.Storage
Authenticator *auth.Authenticator
JWTSecret string
SecureCookies bool
}
func New(db *sqlx.DB, store storage.Storage, authenticator *auth.Authenticator, jwtSecret string, secureCookies bool) *Handlers {
return &Handlers{
DB: db,
Storage: store,
Authenticator: authenticator,
JWTSecret: jwtSecret,
SecureCookies: secureCookies,
}
}
// All queries in this package are written with "?" placeholders (SQLite's
// native style) and go through these three helpers, which rebind to "$1,
// $2, ..." automatically when running against Postgres. This is what lets
// the same query strings work against both DB_DRIVER options.
func (h *Handlers) dbGet(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
return h.DB.GetContext(ctx, dest, h.DB.Rebind(query), args...)
}
func (h *Handlers) dbSelect(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
return h.DB.SelectContext(ctx, dest, h.DB.Rebind(query), args...)
}
func (h *Handlers) dbExec(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
return h.DB.ExecContext(ctx, h.DB.Rebind(query), args...)
}
// writeJSON marshals v as the response body, or 500s if it fails.
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if v == nil {
return
}
if err := json.NewEncoder(w).Encode(v); err != nil {
// Response is already partially written at this point; just log.
// (No logger wired up yet — keep it dead simple and let it be silent
// in the rare case encoding itself fails.)
_ = err
}
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}
// isUniqueConstraintErr distinguishes an actual unique-constraint violation
// (e.g. duplicate rego) from any other DB error, so a schema/column problem
// during development doesn't get mislabeled as "already exists" and hide
// the real cause. Postgres and SQLite word this differently, so it's a
// substring match on the driver's own error text rather than a typed
// sentinel — good enough since the only thing we do with it is pick the
// response code/message, not branch on a specific constraint.
func isUniqueConstraintErr(err error) bool {
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "unique constraint") || strings.Contains(msg, "duplicate key")
}
// page is the response shape for every paginated list endpoint — long lists
// (service history, knowledgebase) load a page at a time instead of
// dumping everything into one response/DOM.
type page[T any] struct {
Items []T `json:"items"`
HasMore bool `json:"hasMore"`
}
const (
defaultPageSize = 20
maxPageSize = 100
)
// parsePagination reads ?limit=&offset= from the query string, applying
// sane defaults/bounds so a bad or missing value can't blow up the page
// size or request something nonsensical.
func parsePagination(r *http.Request) (limit, offset int) {
limit = defaultPageSize
if v, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && v > 0 {
limit = v
}
if limit > maxPageSize {
limit = maxPageSize
}
offset = 0
if v, err := strconv.Atoi(r.URL.Query().Get("offset")); err == nil && v > 0 {
offset = v
}
return limit, offset
}
// paginate expects rows fetched with LIMIT limit+1, so it can tell whether
// there's a next page without a separate COUNT(*) query — then trims back
// down to limit.
func paginate[T any](limit int, rows []T) (trimmed []T, hasMore bool) {
hasMore = len(rows) > limit
if hasMore {
rows = rows[:limit]
}
return rows, hasMore
}