Files
mtusi2026lab4/internal/messenger/httpapi/request.go
T

148 lines
3.9 KiB
Go

package httpapi
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
)
const maxRequestBytes = 1 << 20
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
type createMessageRequest struct {
Text json.RawMessage `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
}
func (r createMessageRequest) values() (string, []string, bool) {
var text *string
if len(r.Text) == 0 || json.Unmarshal(r.Text, &text) != nil || text == nil {
return "", nil, false
}
if len(r.AttachmentIDs) == 0 {
return *text, nil, true
}
var attachmentIDs *[]string
if json.Unmarshal(r.AttachmentIDs, &attachmentIDs) != nil || attachmentIDs == nil {
return "", nil, false
}
return *text, *attachmentIDs, true
}
func readJSON(w http.ResponseWriter, r *http.Request, target any) *apiError {
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
return &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "expected application/json"}
}
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBytes)
data, err := io.ReadAll(r.Body)
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "request body too large"}
}
return invalidRequest()
}
if !utf8.Valid(data) {
return invalidRequest()
}
var object map[string]json.RawMessage
if err := json.Unmarshal(data, &object); err != nil || object == nil {
return invalidRequest()
}
normalized, err := json.Marshal(object)
if err != nil {
return invalidRequest()
}
decoder := json.NewDecoder(bytes.NewReader(normalized))
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
return invalidRequest()
}
return nil
}
func validText(value string, maxRunes int) bool {
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes
}
func idempotencyKey(r *http.Request) (string, bool) {
values := r.Header.Values("Idempotency-Key")
if len(values) != 1 || !idempotencyKeyPattern.MatchString(values[0]) {
return "", false
}
return values[0], true
}
type pageCursor struct {
Kind string `json:"kind"`
Resource string `json:"resource"`
Time time.Time `json:"time"`
ID string `json:"id"`
}
func pageParams(r *http.Request, kind, resource string) (int, *pageCursor, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return 0, nil, invalidRequest()
}
for key := range query {
if key != "limit" && key != "cursor" {
return 0, nil, invalidRequest()
}
if len(query[key]) != 1 {
return 0, nil, invalidRequest()
}
}
limit := 50
if value, present := query["limit"]; present {
parsed, err := strconv.Atoi(value[0])
if err != nil || parsed < 1 || parsed > 100 {
return 0, nil, invalidRequest()
}
limit = parsed
}
if value, present := query["cursor"]; present {
cursor, valid := decodeCursor(value[0], kind, resource)
if !valid {
return 0, nil, invalidRequest()
}
return limit, cursor, nil
}
return limit, nil, nil
}
func encodeCursor(kind, resource string, createdAt time.Time, id string) string {
data, _ := json.Marshal(pageCursor{kind, resource, createdAt, id})
return base64.RawURLEncoding.EncodeToString(data)
}
func decodeCursor(value, kind, resource string) (*pageCursor, bool) {
data, err := base64.RawURLEncoding.DecodeString(value)
if err != nil {
return nil, false
}
var cursor pageCursor
if err := json.Unmarshal(data, &cursor); err != nil || cursor.Kind != kind || cursor.Resource != resource {
return nil, false
}
if cursor.Time.IsZero() {
return nil, false
}
if _, valid := canonicalID(cursor.ID); !valid {
return nil, false
}
return &cursor, true
}