Files
mtusi2026lab4/internal/httpapi/router.go
T
2026-11-05 13:52:11 +03:00

97 lines
2.9 KiB
Go

package httpapi
import (
"net/http"
"sync/atomic"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"mtusi2026/internal/blobstore"
"mtusi2026/internal/cache"
"mtusi2026/internal/model"
"mtusi2026/internal/sessionstore"
"mtusi2026/internal/store"
)
type Options struct {
InstanceID string
Redis *redis.Client
Draining *atomic.Bool
Blobs blobstore.Store
MaxUploads int
}
func NewRouter(s *store.Store, pool *pgxpool.Pool, sessionStores ...sessionstore.Store) http.Handler {
var ss sessionstore.Store
if len(sessionStores) > 0 {
ss = sessionStores[0]
}
return NewRouterWithCache(s, pool, ss, nil)
}
func NewRouterWithCache(
s *store.Store,
pool *pgxpool.Pool,
sessionStore sessionstore.Store,
chatCache *cache.Cache,
opts ...Options,
) http.Handler {
var o Options
if len(opts) > 0 {
o = opts[0]
}
if o.InstanceID == "" {
o.InstanceID = "local"
}
if o.Draining == nil {
o.Draining = new(atomic.Bool)
}
if o.MaxUploads <= 0 {
o.MaxUploads = 4
}
a := &api{
store: s,
sessionStore: sessionStore,
chatCache: chatCache,
blobs: o.Blobs,
uploadSem: make(chan struct{}, o.MaxUploads),
}
apiMux := http.NewServeMux()
apiMux.HandleFunc("POST /api/v1/users", a.handleRegisterUser)
apiMux.HandleFunc("GET /api/v1/users/me", a.authMiddleware(a.handleCurrentUser))
apiMux.HandleFunc("POST /api/v1/chats", a.authMiddleware(a.handleCreateChat))
apiMux.HandleFunc("GET /api/v1/chats", a.authMiddleware(a.handleListChats))
apiMux.HandleFunc("GET /api/v1/chats/{chat_id}", a.authMiddleware(a.handleGetChat))
apiMux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleCreateMessage))
apiMux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleListMessages))
apiMux.HandleFunc("POST /api/v1/auth/sessions", a.handleCreateSession)
apiMux.HandleFunc("POST /api/v1/chats/{chat_id}/attachments", a.authMiddleware(a.handleUploadAttachment))
apiMux.HandleFunc("GET /api/v1/attachments/{attachment_id}", a.authMiddleware(a.handleGetAttachment))
apiMux.HandleFunc("GET /api/v1/attachments/{attachment_id}/content", a.authMiddleware(a.handleDownloadAttachment))
apiMux.HandleFunc("DELETE /api/v1/auth/sessions/current", a.authMiddleware(
func(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
a.handleDeleteSession(w, r)
}))
root := http.NewServeMux()
root.HandleFunc("GET /health/live", handleHealthLive)
root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Blobs, o.Draining))
root.Handle("/", concurrencyMiddleware(s.Limiter, apiMux))
var h http.Handler = root
h = loggingMiddleware(h)
h = instanceMiddleware(o.InstanceID, h)
return h
}
func instanceMiddleware(id string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", id)
next.ServeHTTP(w, r)
})
}