all repos — weimar @ b26a020c4b21a1c0d9a62bc6afdf405ea2097d82

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

internal/api/api.go (view raw)

 1package api
 2
 3import (
 4	"context"
 5	"encoding/json"
 6	"net/http"
 7
 8	"github.com/mjensen/weimar/internal/auth"
 9	"github.com/mjensen/weimar/internal/config"
10	"github.com/mjensen/weimar/internal/db"
11	"github.com/mjensen/weimar/internal/storage"
12)
13
14type ctxKey string
15
16const CtxKeyUser ctxKey = "user"
17
18// UserFromContext extracts the authenticated user from the request context.
19func UserFromContext(ctx context.Context) *db.User {
20	user, _ := ctx.Value(CtxKeyUser).(*db.User)
21	return user
22}
23
24// API holds dependencies shared by all HTTP handlers.
25type API struct {
26	DB      *db.DB
27	Auth    *auth.SessionManager
28	Storage *storage.Storage
29	Cfg     config.Config
30}
31
32func New(database *db.DB, sm *auth.SessionManager, st *storage.Storage, cfg config.Config) *API {
33	return &API{
34		DB:      database,
35		Auth:    sm,
36		Storage: st,
37		Cfg:     cfg,
38	}
39}
40
41func writeJSON(w http.ResponseWriter, status int, v any) {
42	w.Header().Set("Content-Type", "application/json")
43	w.WriteHeader(status)
44	json.NewEncoder(w).Encode(v)
45}
46
47func writeError(w http.ResponseWriter, status int, msg string) {
48	writeJSON(w, status, map[string]string{"error": msg})
49}