Files
pipu-music/services/api/internal/server/router.go
T
mrleo1nidandClaude Opus 5.5 c583991d14
ci / api / api (push) Successful in 26s
ci / mobile / mobile (Metro-бандл Android) (push) Failing after 22s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 37s
ci / ts / ts (packages + web) (push) Successful in 51s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 53s
feat(api): library sources, scanner and catalog (M2)
- schema for sources, path patterns, media files, artists, albums,
  tracks, genres (migration 00003)
- path patterns (RE2 with named groups, skip), merge with tags by
  source priority, fallbacks from the file name and folder, name
  normalization and multi-artist split
- scanner: walk, skip unchanged files by size and mtime, ffprobe in 8
  workers with a single catalog writer, renames by content hash keep
  the track, duplicates fold into one track with the best file as
  primary, missing files are kept 30 days
- storage-agent mounts NFS with validated server, export and an option
  whitelist, no shell; test mount counts audio files
- admin API: sources CRUD, connection test, patterns with preview,
  scan, library status, file errors, host folder picker; scheduled
  scans and health checks; mounts are restored on start
- catalog API: artist, artist albums, album with tracks, track
- api image is alpine with ffmpeg for ffprobe

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 06:48:37 +03:00

71 lines
2.3 KiB
Go

// Package server собирает HTTP-роутер сервиса api из модулей.
package server
import (
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"pipu/api/internal/api/gen"
"pipu/api/internal/auth"
"pipu/api/internal/library"
"pipu/api/internal/platform/httpx"
"pipu/api/internal/system"
)
// Deps — модули, реализующие части контракта API.
type Deps struct {
Log *slog.Logger
System *system.Handler
Auth *auth.Handler
// Library — хранилища, сканы и каталог.
Library *library.Handler
// AuthService проверяет access-токены в middleware. nil — только для тестов служебных эндпоинтов.
AuthService *auth.Service
}
// handlers объединяет модули в единую реализацию gen.StrictServerInterface.
// По мере появления модулей (catalog, ...) они встраиваются сюда.
// Алиасы дают встроенным полям разные имена: у модулей одинаковое имя типа Handler.
type (
systemHandler = system.Handler
authHandler = auth.Handler
libraryHandler = library.Handler
)
type handlers struct {
*systemHandler
*authHandler
*libraryHandler
}
var _ gen.StrictServerInterface = handlers{}
// NewRouter возвращает корневой http.Handler.
func NewRouter(d Deps) http.Handler {
log := d.Log
if log == nil {
log = slog.New(slog.DiscardHandler)
}
r := chi.NewRouter()
r.Use(middleware.RequestID, httpx.RealIP, httpx.AccessLog(log), middleware.Recoverer)
if d.AuthService != nil {
r.Use(auth.Middleware(d.AuthService, log))
}
r.NotFound(httpx.NotFound)
r.MethodNotAllowed(httpx.MethodNotAllowed)
strict := gen.NewStrictHandlerWithOptions(handlers{systemHandler: d.System, authHandler: d.Auth, libraryHandler: d.Library}, nil, gen.StrictHTTPServerOptions{
RequestErrorHandlerFunc: httpx.RequestError,
ResponseErrorHandlerFunc: httpx.ResponseError(log),
})
return gen.HandlerWithOptions(strict, gen.ChiServerOptions{
BaseRouter: r,
// Ошибки разбора path- и query-параметров — тоже problem+json, а не текст по умолчанию.
ErrorHandlerFunc: httpx.RequestError,
})
}