forked from SamohvalovAndreyBPI2302/mtusi2026lab1
ЛР1 на 4: in-memory API, Docker, student-tests и конкурентная проверка.
Реализован контракт lab1 (X-User-Id), non-root образ, SIGTERM ≤10s, DEFENSE/REPORT.
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab1/internal/store"
|
||||
)
|
||||
|
||||
func parseJSON(r *http.Request, dst any) error {
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if ct != "" && !strings.HasPrefix(strings.ToLower(ct), "application/json") {
|
||||
return fmt.Errorf("unsupported media type")
|
||||
}
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return fmt.Errorf("malformed json")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func usernameOK(s string) bool {
|
||||
if len(s) < 3 || len(s) > 32 {
|
||||
return false
|
||||
}
|
||||
for _, c := range s {
|
||||
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func nonBlankRunes(s string) bool {
|
||||
for _, r := range s {
|
||||
if !unicode.IsSpace(r) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func pageParams(r *http.Request, scope string) (int, *store.Bookmark, error) {
|
||||
limit := 50
|
||||
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, nil, fmt.Errorf("invalid limit")
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
if cur := r.URL.Query().Get("cursor"); cur != "" {
|
||||
bm, err := unpackBookmark(cur)
|
||||
if err != nil || bm.Scope != scope {
|
||||
return 0, nil, fmt.Errorf("invalid cursor")
|
||||
}
|
||||
return limit, bm, nil
|
||||
}
|
||||
return limit, nil, nil
|
||||
}
|
||||
|
||||
func packBookmark(b *store.Bookmark) string {
|
||||
raw := fmt.Sprintf("%s|%s|%s", b.Scope, b.CreatedAt.UTC().Format(time.RFC3339Nano), b.ID.String())
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func unpackBookmark(encoded string) (*store.Bookmark, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts := strings.SplitN(string(data), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return nil, fmt.Errorf("bad bookmark")
|
||||
}
|
||||
ts, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &store.Bookmark{Scope: parts[0], CreatedAt: ts.UTC(), ID: id}, nil
|
||||
}
|
||||
|
||||
func tsRFC3339(t time.Time) string {
|
||||
return t.UTC().Format("2006-01-02T15:04:05.000Z")
|
||||
}
|
||||
|
||||
func userWire(u *store.User) map[string]any {
|
||||
return map[string]any{
|
||||
"id": u.ID.String(),
|
||||
"username": u.Username,
|
||||
"display_name": u.DisplayName,
|
||||
"created_at": tsRFC3339(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func chatWire(c *store.Chat) map[string]any {
|
||||
members := make([]string, len(c.MemberIDs))
|
||||
for i, id := range c.MemberIDs {
|
||||
members[i] = id.String()
|
||||
}
|
||||
return map[string]any{
|
||||
"id": c.ID.String(),
|
||||
"title": c.Title,
|
||||
"member_ids": members,
|
||||
"created_at": tsRFC3339(c.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func messageWire(m *store.Message) map[string]any {
|
||||
return map[string]any{
|
||||
"id": m.ID.String(),
|
||||
"chat_id": m.ChatID.String(),
|
||||
"sender_id": m.SenderID.String(),
|
||||
"text": m.Text,
|
||||
"created_at": tsRFC3339(m.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func pageWire(items []map[string]any, next *store.Bookmark) map[string]any {
|
||||
var cursor any
|
||||
if next != nil {
|
||||
cursor = packBookmark(next)
|
||||
}
|
||||
return map[string]any{"items": items, "next_cursor": cursor}
|
||||
}
|
||||
|
||||
func (s *Service) writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func (s *Service) writeErr(w http.ResponseWriter, r *http.Request, status int, code, message string) {
|
||||
rid := reqID(r)
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"error": map[string]any{
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": rid,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func displayNameOK(name string) bool {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return false
|
||||
}
|
||||
return utf8.RuneCountInString(name) <= 100
|
||||
}
|
||||
|
||||
func titleOK(title string) bool {
|
||||
title = strings.TrimSpace(title)
|
||||
if title == "" {
|
||||
return false
|
||||
}
|
||||
return utf8.RuneCountInString(title) <= 100
|
||||
}
|
||||
Reference in New Issue
Block a user