feat: port lab4 implementation
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
"mtusi2026-messenger/internal/httpx"
|
||||
"mtusi2026-messenger/internal/middleware"
|
||||
"mtusi2026-messenger/internal/service"
|
||||
)
|
||||
|
||||
type AttachmentHandler struct {
|
||||
service *service.AttachmentService
|
||||
maxBytes int
|
||||
}
|
||||
|
||||
func NewAttachmentHandler(service *service.AttachmentService, maxBytes int) *AttachmentHandler {
|
||||
return &AttachmentHandler{
|
||||
service: service,
|
||||
maxBytes: maxBytes,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
chatID, err := uuid.Parse(chi.URLParam(r, "chat_id"))
|
||||
if err != nil {
|
||||
httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid chat_id", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
req := dto.CreateAttachmentRequest{
|
||||
Filename: r.URL.Query().Get("filename"),
|
||||
}
|
||||
if !req.Validate() {
|
||||
httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid filename", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
if deadline, ok := r.Context().Deadline(); ok {
|
||||
controller := http.NewResponseController(w)
|
||||
if err := controller.SetReadDeadline(deadline); err != nil {
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
defer func() { _ = controller.SetReadDeadline(time.Time{}) }()
|
||||
}
|
||||
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
r.Body = http.MaxBytesReader(w, r.Body, int64(h.maxBytes))
|
||||
|
||||
att, err := h.service.Upload(r.Context(), userID, chatID, req.Filename, r.Body, contentType)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrUploadReadTimeout):
|
||||
r.Close = true
|
||||
w.Header().Set("Connection", "close")
|
||||
httpx.WriteError(w, http.StatusRequestTimeout, dto.ErrorCodeInvalidRequest, "upload body read timed out", requestID)
|
||||
return
|
||||
case errors.Is(err, service.ErrInvalidSize):
|
||||
httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodePayloadTooLarge, "file too large", requestID)
|
||||
return
|
||||
case errors.Is(err, service.ErrInvalidImage):
|
||||
httpx.WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeUnsupportedMediaType, "invalid image", requestID)
|
||||
return
|
||||
case errors.Is(err, service.ErrAttachmentNotFound):
|
||||
httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID)
|
||||
return
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusCreated, dto.ToAttachmentResponse(att))
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
attachmentID, err := uuid.Parse(chi.URLParam(r, "attachment_id"))
|
||||
if err != nil {
|
||||
httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid attachment_id", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
att, err := h.service.Get(r.Context(), userID, attachmentID)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrAttachmentNotFound):
|
||||
httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID)
|
||||
return
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusOK, dto.ToAttachmentResponse(att))
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) GetContent(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
attachmentID, err := uuid.Parse(chi.URLParam(r, "attachment_id"))
|
||||
if err != nil {
|
||||
httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid attachment_id", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
req := dto.GetAttachmentContentRequest{
|
||||
Variant: r.URL.Query().Get("variant"),
|
||||
}
|
||||
if !req.Validate() {
|
||||
httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
data, contentType, err := h.service.GetContent(r.Context(), userID, attachmentID)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrAttachmentNotReady):
|
||||
httpx.WriteError(w, http.StatusConflict, dto.ErrorCodeConflict, "attachment not ready", requestID)
|
||||
return
|
||||
case errors.Is(err, service.ErrAttachmentNotFound):
|
||||
httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID)
|
||||
return
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", string(contentType))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
"mtusi2026-messenger/internal/httpx"
|
||||
"mtusi2026-messenger/internal/middleware"
|
||||
"mtusi2026-messenger/internal/service"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
service *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(s *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{service: s}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
username, plain, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
httpx.WriteUnauthorized(w, httpx.BasicChallenge, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
if !httpx.RejectBody(w, r, requestID) {
|
||||
return
|
||||
}
|
||||
|
||||
session, err := h.service.Login(r.Context(), username, plain)
|
||||
if errors.Is(err, service.ErrInvalidCredentials) {
|
||||
httpx.WriteUnauthorized(w, httpx.BasicChallenge, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusCreated, dto.SessionResponse{
|
||||
Token: session.Token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: session.ExpiresAt,
|
||||
User: dto.UserResponse{
|
||||
ID: session.User.ID,
|
||||
Username: session.User.Username,
|
||||
DisplayName: session.User.DisplayName,
|
||||
CreatedAt: session.User.CreatedAt,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
token, ok := httpx.BearerToken(r)
|
||||
if !ok {
|
||||
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
err := h.service.Logout(r.Context(), token)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrSessionCacheUnavailable):
|
||||
httpx.WriteError(w, http.StatusServiceUnavailable, dto.ErrorCodeUnavailable, "session cache unavailable", requestID)
|
||||
return
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
|
||||
return
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
"mtusi2026-messenger/internal/httpx"
|
||||
"mtusi2026-messenger/internal/middleware"
|
||||
"mtusi2026-messenger/internal/service"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
service *service.ChatService
|
||||
}
|
||||
|
||||
func NewChatHandler(service *service.ChatService) *ChatHandler {
|
||||
return &ChatHandler{service: service}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
var req dto.CreateChatRequest
|
||||
if !httpx.DecodeJSONBody(w, r, requestID, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
if !req.Validate() {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid request body",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.service.Create(r.Context(), userID, req.Title, req.MemberIDs)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrNotChatMember):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"caller must be a member of member_ids",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case errors.Is(err, service.ErrDuplicateMember):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"member_ids contains duplicates",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case errors.Is(err, service.ErrUnknownMember):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"member_ids contains unknown user",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusCreated, dto.ToChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
chatID, err := uuid.Parse(chi.URLParam(r, "chat_id"))
|
||||
if err != nil {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid chat_id",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.service.Get(r.Context(), userID, chatID)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrChatNotFound):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusNotFound,
|
||||
dto.ErrorCodeNotFound,
|
||||
"chat not found",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusOK, dto.ToChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
limit, cursor, ok := httpx.ParsePagination(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
chats, nextCursor, err := h.service.List(r.Context(), userID, limit, cursor)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrInvalidCursor):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid cursor",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]dto.ChatResponse, 0, len(chats))
|
||||
for _, c := range chats {
|
||||
items = append(items, dto.ToChatResponse(c))
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusOK, dto.ChatPageResponse{
|
||||
Items: items,
|
||||
NextCursor: nextCursor,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
"mtusi2026-messenger/internal/httpx"
|
||||
)
|
||||
|
||||
const readyPingTimeout = 2 * time.Second
|
||||
|
||||
type Pinger interface {
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type HealthHandler struct {
|
||||
log *slog.Logger
|
||||
dependencies []Pinger
|
||||
}
|
||||
|
||||
func NewHealthHandler(log *slog.Logger, dependencies ...Pinger) *HealthHandler {
|
||||
return &HealthHandler{log: log, dependencies: dependencies}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
_ = json.NewEncoder(w).Encode(dto.HealthResponse{
|
||||
Status: "ok",
|
||||
})
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), readyPingTimeout)
|
||||
defer cancel()
|
||||
|
||||
for _, dependency := range h.dependencies {
|
||||
if err := dependency.Ping(ctx); err != nil {
|
||||
h.log.ErrorContext(r.Context(), "readiness check failed", "error", err)
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
dto.ErrorCodeUnavailable,
|
||||
"service unavailable",
|
||||
w.Header().Get("X-Request-Id"),
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
_ = json.NewEncoder(w).Encode(dto.HealthResponse{
|
||||
Status: "ok",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
"mtusi2026-messenger/internal/httpx"
|
||||
"mtusi2026-messenger/internal/middleware"
|
||||
"mtusi2026-messenger/internal/service"
|
||||
)
|
||||
|
||||
var idempotencyKeyReq = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type MessageHandler struct {
|
||||
service *service.MessageService
|
||||
}
|
||||
|
||||
func NewMessageHandler(service *service.MessageService) *MessageHandler {
|
||||
return &MessageHandler{service: service}
|
||||
}
|
||||
|
||||
func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
chatID, err := uuid.Parse(chi.URLParam(r, "chat_id"))
|
||||
if err != nil {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid chat_id",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if !idempotencyKeyReq.MatchString(key) {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid Idempotency-Key",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.CreateMessageRequest
|
||||
if !httpx.DecodeJSONBody(w, r, requestID, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
if !req.Validate() {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid request body",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
attachmentIDs := make([]uuid.UUID, 0, len(req.AttachmentIDs))
|
||||
for _, s := range req.AttachmentIDs {
|
||||
id, err := uuid.Parse(s)
|
||||
if err != nil {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid attachment_id",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
attachmentIDs = append(attachmentIDs, id)
|
||||
}
|
||||
|
||||
message, err := h.service.Create(r.Context(), userID, chatID, key, req.Text, attachmentIDs)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrMessageChatNotFound):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusNotFound,
|
||||
dto.ErrorCodeNotFound,
|
||||
"chat not found",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case errors.Is(err, service.ErrAttachmentNotFound):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusNotFound,
|
||||
dto.ErrorCodeNotFound,
|
||||
"attachment not found",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case errors.Is(err, service.ErrAttachmentNotReady):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusConflict,
|
||||
dto.ErrorCodeConflict,
|
||||
"attachment not ready",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case errors.Is(err, service.ErrIdempotencyKeyConflict):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusConflict,
|
||||
dto.ErrorCodeConflict,
|
||||
"idempotency key reused with different request",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusCreated, dto.ToMessageResponse(message))
|
||||
}
|
||||
|
||||
func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
chatID, err := uuid.Parse(chi.URLParam(r, "chat_id"))
|
||||
if err != nil {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid chat_id",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
limit, cursor, ok := httpx.ParsePagination(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
messages, nextCursor, err := h.service.List(r.Context(), userID, chatID, limit, cursor)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrMessageChatNotFound):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusNotFound,
|
||||
dto.ErrorCodeNotFound,
|
||||
"chat not found",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case errors.Is(err, service.ErrInvalidCursor):
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid cursor",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
case err != nil:
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]dto.MessageResponse, 0, len(messages))
|
||||
for _, m := range messages {
|
||||
items = append(items, dto.ToMessageResponse(m))
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusOK, dto.MessagePageResponse{
|
||||
Items: items,
|
||||
NextCursor: nextCursor,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
"mtusi2026-messenger/internal/httpx"
|
||||
"mtusi2026-messenger/internal/middleware"
|
||||
"mtusi2026-messenger/internal/service"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
service *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(service *service.UserService) *UserHandler {
|
||||
return &UserHandler{service: service}
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
var req dto.CreateUserRequest
|
||||
if !httpx.DecodeJSONBody(w, r, requestID, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
if !req.Validate() {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"invalid request body",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.service.Create(
|
||||
r.Context(),
|
||||
req.Username,
|
||||
req.DisplayName,
|
||||
req.Password,
|
||||
)
|
||||
if errors.Is(err, service.ErrUsernameTaken) {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusConflict,
|
||||
dto.ErrorCodeConflict,
|
||||
"username already taken",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusCreated, dto.UserResponse{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: user.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
user, err := h.service.GetByID(r.Context(), userID)
|
||||
if errors.Is(err, service.ErrUserNotFound) {
|
||||
httpx.WriteError(
|
||||
w,
|
||||
http.StatusNotFound,
|
||||
dto.ErrorCodeNotFound,
|
||||
"user not found",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
httpx.WriteInternalError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusOK, dto.UserResponse{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: user.CreatedAt,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user