Files
glchat/internal/httpx/errors.go
T
grendervill 2bf7101f2d chore(lint): настроить golangci-lint v2, gofumpt и форматирование в make
- .golangci.yml: набор линтеров под требования §14 (gosec, gocritic, sloglint,
  noctx, revive, depguard для запрета циклических зависимостей internal/*)
- gofumpt вынесен из formatters golangci-lint v2.13 (сообщал о расхождениях,
  которые сам же не устранял) и применяется отдельным инструментом
- make fmt/go-lint: проверка gofumpt + golangci-lint fmt --diff
- scripts/gitleaks-scan.sh: поддержка gitleaks 8.19+ (dir) и старых версий (detect)
- исправлены замечания линтеров: обработка ошибок Close, контекст в логах,
  NewRequestWithContext в тестах, комментарий к blank-import драйвера SQLite
2026-09-19 18:25:20 +03:00

71 lines
1.7 KiB
Go

package httpx
import (
"encoding/json"
"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 CodeInternalError:
return http.StatusInternalServerError
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", slog.Any("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() }