forked from mtusi2026/mtusi2026lab2
81 lines
2.0 KiB
Go
81 lines
2.0 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"messenger/src/backend/services"
|
|
)
|
|
|
|
type createUserRequest struct {
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
func decodeJSONBody(r *http.Request, destination any) error {
|
|
decoder := json.NewDecoder(r.Body)
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(destination); err != nil {
|
|
return err
|
|
}
|
|
var extra any
|
|
if err := decoder.Decode(&extra); err != io.EOF {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return fmt.Errorf("more than one JSON value")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func createUserHandler(users *services.UserService) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
requestID := newRequestID()
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
if r.Method != http.MethodPost {
|
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
|
return
|
|
}
|
|
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
|
|
writeError(w, 415, "unsupported_media_type", "content type must be application/json", requestID)
|
|
return
|
|
}
|
|
var request createUserRequest
|
|
if err := decodeJSONBody(r, &request); err != nil {
|
|
writeError(w, 400, "invalid_request", "invalid JSON body", requestID)
|
|
return
|
|
}
|
|
user, err := users.Create(r.Context(), request.Username, request.DisplayName, request.Password)
|
|
if err != nil {
|
|
writeServiceError(w, err, requestID)
|
|
return
|
|
}
|
|
writeJSON(w, 201, user)
|
|
}
|
|
}
|
|
|
|
func currentUserHandler(users *services.UserService) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
requestID := newRequestID()
|
|
w.Header().Set("X-Request-Id", requestID)
|
|
if r.Method != http.MethodGet {
|
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
|
return
|
|
}
|
|
userID, ok := requestUserID(w, r, requestID)
|
|
if !ok {
|
|
return
|
|
}
|
|
user, err := users.Get(r.Context(), userID)
|
|
if err != nil {
|
|
writeServiceError(w, err, requestID)
|
|
return
|
|
}
|
|
writeJSON(w, 200, user)
|
|
}
|
|
}
|