Files
Docwell/Server/internal/httpapi/router.go
T
tajniak81andClaude Opus 5.5 ba394b8fac Finish Phase 0: lint, codegen, contributor docs and the two remaining spikes
Repository basics:
- CONTRIBUTING.md and CODE_OF_CONDUCT.md (Contributor Covenant 2.1)
- SPDX AGPL-3.0-or-later headers on all hand-written sources, checked in CI
- golangci-lint (shared .golangci.yml), ESLint and Prettier, all run in CI

API codegen from api/openapi.yaml (npm run generate, drift fails CI):
- Go types via oapi-codegen in Server/internal/api
- a contract test that the router and the spec list the same routes
- Dart models via Phone-App/tool/generate_api.dart; the app uses them

Spike: shared Tiptap editor in a Flutter WebView (ADR-4)
- @docwell/editor-bridge builds the editor into one HTML page with a
  versioned JSON protocol; Phone-App hosts it with webview_flutter and a
  native toolbar. Integration test passes on an Android API 35 emulator.
- flutter_inappwebview dropped: its Android plugin fails on AGP 9.

Spike: Wails v3 desktop (ADR-11)
- system tray, docwell:// deep links (page and space only) with
  single-instance hand-off, and the built-in updater with a required
  ed25519 signing key. Verified on Windows.
- regenerated build assets register the scheme and drop template
  placeholders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:11:07 +01:00

133 lines
3.9 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
// 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
Directory DirectoryService
// Collab serves /collab; nil disables live editing.
Collab CollabHub
Admin http.Handler
Log *slog.Logger
}
// routeMux is a ServeMux that remembers its patterns, so a test can compare
// them with api/openapi.yaml.
type routeMux struct {
*http.ServeMux
patterns []string
}
func (m *routeMux) Handle(pattern string, h http.Handler) {
m.patterns = append(m.patterns, pattern)
m.ServeMux.Handle(pattern, h)
}
func (m *routeMux) HandleFunc(pattern string, h func(http.ResponseWriter, *http.Request)) {
m.Handle(pattern, http.HandlerFunc(h))
}
func NewRouter(d Deps) http.Handler {
return logRequests(d.Log, cors(d.CORSOrigins, newMux(d)))
}
func newMux(d Deps) *routeMux {
mux := &routeMux{ServeMux: http.NewServeMux()}
a := &api{auth: d.Auth, dir: d.Directory, collab: d.Collab, log: d.Log}
a.routes(mux)
a.collabRoute(mux, d.CORSOrigins)
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 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
}
// Unwrap lets the WebSocket upgrade reach the connection's Hijacker.
func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
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))
})
}