Files
mtusi2026lab4/internal/httpapi/router.go
T

91 lines
1.7 KiB
Go

package httpapi
import (
"net/http"
"strings"
"sync/atomic"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
)
type API struct {
messenger *service.Messenger
}
func NewHandler(
messenger *service.Messenger,
stoppingFlags ...*atomic.Bool,
) http.Handler {
api := &API{messenger: messenger}
var stopping *atomic.Bool
if len(stoppingFlags) > 0 {
stopping = stoppingFlags[0]
}
if stopping == nil {
stopping = &atomic.Bool{}
}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if stopping.Load() && r.URL.Path != "/health/live" {
writeError(
w,
http.StatusServiceUnavailable,
"unavailable",
"Server is shutting down",
)
return
}
api.route(w, r)
})
return withInstanceID(withRequestID(withAccessLog(handler)))
}
func (api *API) route(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/v1/chats" ||
strings.HasPrefix(r.URL.Path, "/api/v1/chats/") {
api.authenticate(http.HandlerFunc(api.chatRoutes)).ServeHTTP(w, r)
return
}
switch r.URL.Path {
case "/health/live", "/health/ready":
handleHealth(w, r)
case "/api/v1/users":
if !requireMethod(w, r, http.MethodPost) {
return
}
api.createUser(w, r)
case "/api/v1/users/me":
if !requireMethod(w, r, http.MethodGet) {
return
}
api.authenticate(http.HandlerFunc(api.currentUser)).ServeHTTP(w, r)
default:
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
}
}
func requireMethod(w http.ResponseWriter, r *http.Request, method string) bool {
if r.Method == method {
return true
}
w.Header().Set("Allow", method)
writeError(
w,
http.StatusMethodNotAllowed,
"invalid_request",
"Method not allowed",
)
return false
}