sonda/internal/api/http/router.go
tgiachi 3a739dc3ae feat: add sondad server with config, storage, auth and listening API
- feat(config): TOML config with env overrides, strict parsing and validation
- feat(storage): SQLite (modernc) and PostgreSQL (pgx) backends through bun,
  embedded per-driver SQL migrations with a transactional runner
- feat(schema): catalog tables (artists, albums, tracks, audio_files with
  per-root paths), users and listening events with idempotency keys
- feat(auth): Argon2id password hashing, HS256 JWT tokens, first-user-only
  registration and login
- feat(api): gin REST API under /api/v1 (health, register, login, listens)
  with a consistent error envelope, body limit and request logging
- feat(sondad): zap logger, graceful shutdown, composition root in main
- chore: example config, .gitignore for secrets, DB files, IDE and agent files
2026-11-11 12:06:15 +01:00

64 lines
1.6 KiB
Go

// Package httpapi is the first-party REST API (/api/v1).
//
// Handlers stay thin: they validate and serialize, then call services.
package httpapi
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"codeberg.org/squidd/sonda/internal/auth"
"codeberg.org/squidd/sonda/internal/listening"
)
// maxBodyBytes bounds every request body.
const maxBodyBytes = 64 << 10
type authService interface {
Register(ctx context.Context, username, password string) (auth.User, error)
Login(ctx context.Context, username, password string) (auth.LoginResult, error)
}
type tokenParser interface {
Parse(token string) (auth.Claims, error)
}
type listenService interface {
Record(ctx context.Context, e listening.Event) (bool, error)
}
// Deps are the services the API needs.
type Deps struct {
Logger *zap.Logger
Auth authService
Tokens tokenParser
Listening listenService
}
// NewRouter builds the gin engine with all routes.
func NewRouter(d Deps) *gin.Engine {
r := gin.New()
_ = r.SetTrustedProxies(nil) // use the socket address; no forwarded-header trust yet
r.Use(gin.Recovery(), limitBody(maxBodyBytes), requestLog(d.Logger))
r.NoRoute(func(c *gin.Context) { writeError(c, http.StatusNotFound, "not_found", "no such route") })
v1 := r.Group("/api/v1")
v1.GET("/health", health)
a := &authHandlers{svc: d.Auth}
v1.POST("/auth/register", a.register)
v1.POST("/auth/login", a.login)
protected := v1.Group("", requireAuth(d.Tokens))
l := &listenHandlers{svc: d.Listening}
protected.POST("/listens", l.record)
return r
}
func health(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}