forked from mtusi2026/mtusi2026lab4
111 lines
2.8 KiB
Go
111 lines
2.8 KiB
Go
package api
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"mime"
|
|
"net/http"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"mtusi-messenger/internal/apperr"
|
|
"mtusi-messenger/internal/store"
|
|
)
|
|
|
|
const maxBodyBytes = 1 << 20
|
|
|
|
var (
|
|
usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
|
idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
|
)
|
|
|
|
func messageFingerprint(req createMessageReq) []byte {
|
|
b, _ := json.Marshal(req)
|
|
sum := sha256.Sum256(b)
|
|
return sum[:]
|
|
}
|
|
|
|
func parseUUID(s string) (string, error) {
|
|
u, err := uuid.Parse(s)
|
|
if err != nil || u.String() != s {
|
|
return "", errors.New("invalid uuid")
|
|
}
|
|
return u.String(), nil
|
|
}
|
|
|
|
func runeLen(s string) int { return utf8.RuneCountInString(s) }
|
|
|
|
func validText(s string, max int) bool {
|
|
n := runeLen(s)
|
|
return n >= 1 && n <= max && strings.TrimSpace(s) != ""
|
|
}
|
|
|
|
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) *apperr.AppError {
|
|
media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
|
if media != "application/json" {
|
|
return apperr.UnsupportedMedia("Content-Type must be application/json")
|
|
}
|
|
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes)
|
|
dec := json.NewDecoder(r.Body)
|
|
dec.DisallowUnknownFields()
|
|
if err := dec.Decode(dst); err != nil {
|
|
var maxErr *http.MaxBytesError
|
|
if errors.As(err, &maxErr) {
|
|
return apperr.PayloadTooLarge("request body too large")
|
|
}
|
|
return apperr.InvalidRequest("malformed JSON body")
|
|
}
|
|
var extra json.RawMessage
|
|
if err := dec.Decode(&extra); err != io.EOF {
|
|
var maxErr *http.MaxBytesError
|
|
if errors.As(err, &maxErr) {
|
|
return apperr.PayloadTooLarge("request body too large")
|
|
}
|
|
return apperr.InvalidRequest("malformed JSON body")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func pagingParams(r *http.Request, scope string) (int, *store.Cursor, *apperr.AppError) {
|
|
limit := 50
|
|
if v := r.URL.Query().Get("limit"); v != "" {
|
|
n, err := strconv.Atoi(v)
|
|
if err != nil || n < 1 || n > 100 {
|
|
return 0, nil, apperr.InvalidRequest("limit must be an integer in 1..100")
|
|
}
|
|
limit = n
|
|
}
|
|
var cur *store.Cursor
|
|
if v := r.URL.Query().Get("cursor"); v != "" {
|
|
c, err := store.DecodeCursor(v)
|
|
if err == nil {
|
|
_, err = parseUUID(c.ID)
|
|
}
|
|
if err != nil {
|
|
return 0, nil, apperr.InvalidRequest("invalid cursor")
|
|
}
|
|
if c.Scope != scope {
|
|
return 0, nil, apperr.InvalidRequest("cursor does not belong to this resource")
|
|
}
|
|
cur = &c
|
|
}
|
|
return limit, cur, nil
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, r *http.Request, status int, payload any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.Header().Set("X-Request-Id", requestID(r))
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(payload)
|
|
}
|
|
|
|
func methodNotAllowed(w http.ResponseWriter, r *http.Request) {
|
|
apperr.Write(w, requestID(r), apperr.New(http.StatusMethodNotAllowed, apperr.CodeInvalidRequest, "method not allowed"))
|
|
}
|