forked from mtusi2026/mtusi2026lab2
221 lines
6.4 KiB
Go
221 lines
6.4 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"mime"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
v10 "github.com/go-playground/validator/v10"
|
|
"github.com/google/uuid"
|
|
|
|
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
|
|
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
|
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
|
)
|
|
|
|
const (
|
|
HeaderContentType = "Content-Type"
|
|
HeaderRequestID = "X-Request-Id"
|
|
HeaderUserID = "X-User-Id"
|
|
)
|
|
|
|
type Handler interface {
|
|
RegisterRoutes()
|
|
}
|
|
|
|
type BaseHandler struct {
|
|
router chi.Router
|
|
validator *validator.ValidatorImpl
|
|
}
|
|
|
|
func NewBaseHandler(r chi.Router) *BaseHandler {
|
|
return &BaseHandler{
|
|
router: r,
|
|
validator: validator.NewValidatorImpl(),
|
|
}
|
|
}
|
|
|
|
func (h *BaseHandler) validate(ctx context.Context, value any) error {
|
|
err := h.validator.ValidateCtx(ctx, value)
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var fieldErrors v10.ValidationErrors
|
|
if errors.As(err, &fieldErrors) {
|
|
return apperr.Wrap(err, apperr.CodeInvalidRequest, "invalid request fields")
|
|
}
|
|
return apperr.Wrap(err, apperr.CodeInternalError, "validation failed")
|
|
}
|
|
|
|
func (h *BaseHandler) Validate(w http.ResponseWriter, r *http.Request, value any) bool {
|
|
if err := h.validate(r.Context(), value); err != nil {
|
|
h.JSONError(r.Context(), w, err)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (h *BaseHandler) JSONResponse(w http.ResponseWriter, status int, body any) {
|
|
w.Header().Set(HeaderContentType, "application/json")
|
|
w.WriteHeader(status)
|
|
|
|
if status == http.StatusNoContent {
|
|
return
|
|
}
|
|
|
|
if err := json.NewEncoder(w).Encode(body); err != nil {
|
|
wrapped := apperr.Wrap(err, apperr.CodeInternal, "failed json encode")
|
|
slog.Error("response", "error", wrapped)
|
|
}
|
|
}
|
|
|
|
func (h *BaseHandler) JSONError(ctx context.Context, w http.ResponseWriter, err error) {
|
|
if err == nil {
|
|
return
|
|
}
|
|
|
|
requestId, ok := ctx.Value(HeaderRequestID).(uuid.UUID)
|
|
if !ok {
|
|
requestId = uuid.New()
|
|
}
|
|
w.Header().Set(HeaderRequestID, requestId.String())
|
|
|
|
appErr, ok := apperr.As(err)
|
|
if !ok {
|
|
appErr = apperr.New(apperr.CodeInternalError, "internal server error")
|
|
}
|
|
slog.Error("response", "error", err, "status", appErr.Code().HTTPStatus(), "requestId", requestId.String())
|
|
h.JSONResponse(w, appErr.Code().HTTPStatus(), contracts.Error{
|
|
Error: struct {
|
|
Code contracts.ErrorErrorCode `json:"code"`
|
|
Message string `json:"message"`
|
|
RequestId string `json:"request_id"`
|
|
}{
|
|
Code: contracts.ErrorErrorCode(appErr.Code()),
|
|
Message: apperr.PublicMessage(appErr),
|
|
RequestId: requestId.String(),
|
|
},
|
|
})
|
|
}
|
|
|
|
func (h *BaseHandler) Decode(w http.ResponseWriter, r *http.Request, object any) bool {
|
|
mediaType, params, err := mime.ParseMediaType(r.Header.Get(HeaderContentType))
|
|
if err != nil || mediaType != "application/json" ||
|
|
(params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
|
|
h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected application/json"))
|
|
return false
|
|
}
|
|
decoder := json.NewDecoder(r.Body)
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(object); err != nil {
|
|
h.JSONError(r.Context(), w, apperr.Wrap(err, apperr.CodeBadRequest, "failed decode"))
|
|
return false
|
|
}
|
|
var trailing any
|
|
if err := decoder.Decode(&trailing); err != io.EOF {
|
|
h.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one JSON object"))
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (h *BaseHandler) PathParam(r *http.Request, key string) string {
|
|
return chi.URLParam(r, key)
|
|
}
|
|
|
|
func (h *BaseHandler) QueryParam(r *http.Request, key string) string {
|
|
return r.URL.Query().Get(key)
|
|
}
|
|
|
|
func (h *BaseHandler) HeaderParam(r *http.Request, key string) string {
|
|
return r.Header.Get(key)
|
|
}
|
|
|
|
func (h *BaseHandler) ParseIDFromPathParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
|
rawID := h.PathParam(r, key)
|
|
id, err := uuid.Parse(rawID)
|
|
if err != nil {
|
|
h.JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
|
return uuid.Nil, err
|
|
}
|
|
return id, nil
|
|
}
|
|
|
|
func (h *BaseHandler) ParseIDFromQueryParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
|
rawID := h.QueryParam(r, key)
|
|
id, err := uuid.Parse(rawID)
|
|
if err != nil {
|
|
h.JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
|
return uuid.Nil, err
|
|
}
|
|
return id, nil
|
|
}
|
|
|
|
func (h *BaseHandler) ParseIDFromHeaderParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
|
rawID := h.HeaderParam(r, key)
|
|
id, err := uuid.Parse(rawID)
|
|
if err != nil {
|
|
h.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing or invalid user ID"))
|
|
return uuid.Nil, err
|
|
}
|
|
return id, nil
|
|
}
|
|
|
|
func (h *BaseHandler) authenticatedUser(w http.ResponseWriter, r *http.Request, users inmemory.UserCache) (dto.User, bool) {
|
|
id, err := h.ParseIDFromHeaderParam(r.Context(), w, r, HeaderUserID)
|
|
if err != nil {
|
|
return dto.User{}, false
|
|
}
|
|
user, err := users.GetByID(r.Context(), id)
|
|
if err != nil {
|
|
if appErr, ok := apperr.As(err); ok && appErr.Code() == apperr.CodeNotFound {
|
|
h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnauthorized, "unknown user ID"))
|
|
} else {
|
|
h.JSONError(r.Context(), w, err)
|
|
}
|
|
return dto.User{}, false
|
|
}
|
|
return user, true
|
|
}
|
|
|
|
func (h *BaseHandler) pageParams(w http.ResponseWriter, r *http.Request) (*int, *uuid.UUID, bool) {
|
|
query := r.URL.Query()
|
|
var limit *int
|
|
if values, exists := query["limit"]; exists {
|
|
if len(values) != 1 {
|
|
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid limit"))
|
|
return nil, nil, false
|
|
}
|
|
value, err := strconv.Atoi(values[0])
|
|
if err != nil || value < 1 || value > 100 {
|
|
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid limit"))
|
|
return nil, nil, false
|
|
}
|
|
limit = &value
|
|
}
|
|
var afterID *uuid.UUID
|
|
if values, exists := query["cursor"]; exists {
|
|
if len(values) != 1 {
|
|
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid cursor"))
|
|
return nil, nil, false
|
|
}
|
|
id, err := uuid.Parse(values[0])
|
|
if err != nil || id == uuid.Nil {
|
|
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid cursor"))
|
|
return nil, nil, false
|
|
}
|
|
afterID = &id
|
|
}
|
|
return limit, afterID, true
|
|
}
|