69aa98e18c
- internal/config: конфигурация из env с валидацией и дефолтами (§5.1, §9.1) - internal/httpx: middleware (request id, slog-логи, recover, security-заголовки), единый формат ошибок §8.5 и лимит тела запроса - internal/database: SQLite WAL + busy_timeout + foreign_keys, один writer и пул чтения, goose-миграции embedded, PRAGMA optimize по расписанию - internal/meta: полезная нагрузка /api/v1/meta (версия, фичи, лимиты) - internal/server: маршруты, SPA-раздача собранного клиента, OpenAPI 3.1 - cmd/glchat: точка входа с graceful shutdown и JSON-логами - тесты: конфиг, миграции и идемпотентность, HTTP-эндпоинты, статика, 404/405
72 lines
1.7 KiB
Go
72 lines
1.7 KiB
Go
package httpx
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
)
|
|
|
|
type ErrorCode string
|
|
|
|
const (
|
|
CodeInternalError ErrorCode = "internal.error"
|
|
CodeNotFound ErrorCode = "not_found"
|
|
CodeBadRequest ErrorCode = "request.bad"
|
|
CodeRateLimited ErrorCode = "ratelimit.hit"
|
|
CodeNotReady ErrorCode = "instance.not_ready"
|
|
)
|
|
|
|
type Error struct {
|
|
Code ErrorCode `json:"code"`
|
|
Message string `json:"message"`
|
|
Details any `json:"details,omitempty"`
|
|
}
|
|
|
|
type errorEnvelope struct {
|
|
Error Error `json:"error"`
|
|
}
|
|
|
|
func (e Error) HTTPStatus() int {
|
|
switch e.Code {
|
|
case CodeNotFound:
|
|
return http.StatusNotFound
|
|
case CodeBadRequest:
|
|
return http.StatusBadRequest
|
|
case CodeRateLimited:
|
|
return http.StatusTooManyRequests
|
|
case CodeNotReady:
|
|
return http.StatusServiceUnavailable
|
|
default:
|
|
return http.StatusInternalServerError
|
|
}
|
|
}
|
|
|
|
func NewError(code ErrorCode, message string) Error {
|
|
return Error{Code: code, Message: message}
|
|
}
|
|
|
|
func WriteJSON(w http.ResponseWriter, status int, body any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.WriteHeader(status)
|
|
if body == nil {
|
|
return
|
|
}
|
|
if err := json.NewEncoder(w).Encode(body); err != nil {
|
|
slog.Error("write json response", "error", err)
|
|
}
|
|
}
|
|
|
|
func WriteError(w http.ResponseWriter, apiErr Error) {
|
|
WriteJSON(w, apiErr.HTTPStatus(), errorEnvelope{Error: apiErr})
|
|
}
|
|
|
|
func WriteErrorStatus(w http.ResponseWriter, status int, code ErrorCode, message string) {
|
|
WriteJSON(w, status, errorEnvelope{Error: NewError(code, message)})
|
|
}
|
|
|
|
func StatusForCode(code ErrorCode) int { return NewError(code, "").HTTPStatus() }
|
|
|
|
var errBodyTooLarge = errors.New("request body too large")
|