Files
Docwell/Server/internal/httpapi/router.go
T
tajniak81andClaude Opus 5.5 4903bb12dd Scaffold Docwell monorepo with PocketBase authentication
Phase 0 foundation for Docwell, an open-source knowledge base:

- Database: PocketBase v0.40.6 with initial schema migrations; users is
  the built-in auth collection, plus a hook for token checks and
  env-driven app URL/SMTP settings
- Server: Go API (health, version, auth endpoints forwarded to
  PocketBase, admin user list) with an embedded Vue admin panel
- Web-App: Go static server and Vue/Tailwind app with Tiptap editor,
  sign-in, sign-up, password reset and email verification (EN/PL)
- Desktop-App: Wails v3 host reusing the web app
- Phone-App: Flutter app with sign-in
- Shared packages (editor, ui, api-client), OpenAPI spec, Docker
  compose (separate services and all-in-one), GitHub Actions CI
- Docs: feature inventory and architecture/build plan

Licensed under AGPL-3.0-or-later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 22:18:25 +01:00

103 lines
3.0 KiB
Go

// Package httpapi wires the public HTTP surface of docwell-server.
package httpapi
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"slices"
"time"
)
// Pinger reports whether a dependency is reachable.
type Pinger interface {
Health(ctx context.Context) error
}
type Deps struct {
Version string
CORSOrigins []string
DB Pinger
Auth AuthService
Admin http.Handler
Log *slog.Logger
}
func NewRouter(d Deps) http.Handler {
mux := http.NewServeMux()
(&api{auth: d.Auth, log: d.Log}).routes(mux)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
if err := d.DB.Health(ctx); err != nil {
d.Log.Warn("readiness check failed", "err", err)
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"status": "unavailable", "db": err.Error()})
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok", "db": "ok"})
})
mux.HandleFunc("GET /api/v1/version", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"name": "docwell-server", "version": d.Version})
})
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not_found"})
})
if d.Admin != nil {
mux.Handle("GET /admin/", d.Admin)
mux.Handle("GET /admin", http.RedirectHandler("/admin/", http.StatusMovedPermanently))
}
return logRequests(d.Log, cors(d.CORSOrigins, mux))
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func cors(origins []string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" && slices.Contains(origins, origin) {
h := w.Header()
h.Set("Access-Control-Allow-Origin", origin)
h.Set("Access-Control-Allow-Credentials", "true")
h.Add("Vary", "Origin")
if r.Method == http.MethodOptions {
h.Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
h.Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
h.Set("Access-Control-Max-Age", "600")
w.WriteHeader(http.StatusNoContent)
return
}
}
next.ServeHTTP(w, r)
})
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (s *statusRecorder) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}
func logRequests(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
log.Info("http", "method", r.Method, "path", r.URL.Path, "status", rec.status, "dur", time.Since(start))
})
}