- internal/logging: LOG_LEVEL/LOG_FORMAT parsing and slog handler - request_id middleware (X-Request-ID or generated, echoed) + debug access log - httpx registers errors; middleware logs internal causes with request_id - health excluded, objects/sse debug-only, no query/body/secrets in logs - new observability capability spec; README/.env.example docs
74 lines
1.8 KiB
Go
74 lines
1.8 KiB
Go
package httpx
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type ErrorBody struct {
|
|
Code string `json:"code"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
type ErrorResponse struct {
|
|
Error ErrorBody `json:"error"`
|
|
}
|
|
|
|
type AppError struct {
|
|
Status int
|
|
Code string
|
|
Message string
|
|
}
|
|
|
|
func (e *AppError) Error() string { return e.Message }
|
|
|
|
func NewError(status int, code, message string) *AppError {
|
|
return &AppError{Status: status, Code: code, Message: message}
|
|
}
|
|
|
|
func BadRequest(code, message string) *AppError {
|
|
return NewError(http.StatusBadRequest, code, message)
|
|
}
|
|
|
|
func Unauthorized(code, message string) *AppError {
|
|
return NewError(http.StatusUnauthorized, code, message)
|
|
}
|
|
|
|
func Forbidden(code, message string) *AppError {
|
|
return NewError(http.StatusForbidden, code, message)
|
|
}
|
|
|
|
func NotFound(code, message string) *AppError {
|
|
return NewError(http.StatusNotFound, code, message)
|
|
}
|
|
|
|
func Conflict(code, message string) *AppError {
|
|
return NewError(http.StatusConflict, code, message)
|
|
}
|
|
|
|
func Internal(message string) *AppError {
|
|
return NewError(http.StatusInternalServerError, "internal_error", message)
|
|
}
|
|
|
|
func Abort(c *gin.Context, err error) {
|
|
_ = c.Error(err)
|
|
var appErr *AppError
|
|
if errors.As(err, &appErr) {
|
|
c.AbortWithStatusJSON(appErr.Status, ErrorResponse{ErrorBody{appErr.Code, appErr.Message}})
|
|
return
|
|
}
|
|
c.AbortWithStatusJSON(http.StatusInternalServerError, ErrorResponse{ErrorBody{"internal_error", "internal server error"}})
|
|
}
|
|
|
|
func RespondError(c *gin.Context, err error) {
|
|
_ = c.Error(err)
|
|
var appErr *AppError
|
|
if errors.As(err, &appErr) {
|
|
c.JSON(appErr.Status, ErrorResponse{ErrorBody{appErr.Code, appErr.Message}})
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, ErrorResponse{ErrorBody{"internal_error", "internal server error"}})
|
|
}
|