package httpapi import ( "crypto/rand" "encoding/hex" "encoding/json" "errors" "io" "mime" "net/http" "time" "mtusi.local/messenger/internal/jsonstrict" "mtusi.local/messenger/internal/model" ) type statusWriter struct { http.ResponseWriter status int wrote bool } func (w *statusWriter) WriteHeader(status int) { if w.wrote { return } w.status = status w.wrote = true w.ResponseWriter.WriteHeader(status) } func (w *statusWriter) Write(body []byte) (int, error) { if !w.wrote { w.status = http.StatusOK w.wrote = true } return w.ResponseWriter.Write(body) } type apiTime time.Time func (t apiTime) MarshalJSON() ([]byte, error) { return []byte(`"` + model.FormatTime(time.Time(t)) + `"`), nil } type userJSON struct { ID string `json:"id"` Username string `json:"username"` DisplayName string `json:"display_name"` CreatedAt apiTime `json:"created_at"` } type chatJSON struct { ID string `json:"id"` Title string `json:"title"` MemberIDs []string `json:"member_ids"` CreatedAt apiTime `json:"created_at"` } type messageJSON struct { ID string `json:"id"` ChatID string `json:"chat_id"` SenderID string `json:"sender_id"` Text string `json:"text"` CreatedAt apiTime `json:"created_at"` } type chatPageJSON struct { Items []chatJSON `json:"items"` NextCursor *string `json:"next_cursor"` } type messagePageJSON struct { Items []messageJSON `json:"items"` NextCursor *string `json:"next_cursor"` } type sessionJSON struct { Token string `json:"token"` TokenType string `json:"token_type"` ExpiresAt apiTime `json:"expires_at"` User userJSON `json:"user"` } func userToJSON(user model.User) userJSON { return userJSON{ ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: apiTime(user.CreatedAt), } } func chatToJSON(chat model.Chat) chatJSON { members := chat.MemberIDs if members == nil { members = []string{} } return chatJSON{ ID: chat.ID, Title: chat.Title, MemberIDs: members, CreatedAt: apiTime(chat.CreatedAt), } } func messageToJSON(msg model.Message) messageJSON { return messageJSON{ ID: msg.ID, ChatID: msg.ChatID, SenderID: msg.SenderID, Text: msg.Text, CreatedAt: apiTime(msg.CreatedAt), } } func writeJSON(w http.ResponseWriter, status int, value any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(status) enc := json.NewEncoder(w) enc.SetEscapeHTML(false) _ = enc.Encode(value) } func writeError(w http.ResponseWriter, status int, code, message, requestID string) { writeJSON(w, status, map[string]any{ "error": map[string]string{ "code": code, "message": message, "request_id": requestID, }, }) } func writeUnauthorized(w http.ResponseWriter, r *http.Request, basic bool) { if basic { w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`) } else { w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`) } writeError(w, http.StatusUnauthorized, "unauthorized", "Нет действительной идентификации", requestID(r)) } func readJSON(w http.ResponseWriter, r *http.Request, dst any) error { media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil || media != "application/json" { return errBadJSON } body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64*1024)) if err != nil { var tooBig *http.MaxBytesError if errors.As(err, &tooBig) { return errTooLarge } return errBadJSON } if err := jsonstrict.Decode(body, dst); err != nil { return errBadJSON } return nil } func bodyEmpty(r *http.Request) bool { if r.Body == nil { return true } buf := make([]byte, 1) n, err := r.Body.Read(buf) if n > 0 { return false } return err == io.EOF || err == nil } func newRequestID() string { var raw [16]byte if _, err := rand.Read(raw[:]); err != nil { return "request" } return hex.EncodeToString(raw[:]) } var ( errBadJSON = errors.New("bad json") errTooLarge = errors.New("too large") )