package handler import ( "io" "mime" "net/http" "strconv" "uuid" "github.com/go-chi/chi/v5" ) func (h *Handler) UploadAttachment(w http.ResponseWriter, r *http.Request) { chatID, err := chatIDParam(r) if err != nil { h.fail(w, r, err) return } filename := r.URL.Query().Get("filename") if filename == "" { h.fail(w, r, badRequest("filename is required")) return } contentType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil { contentType = "" } attachment, err := h.attachments.Upload(r.Context(), actor(r), chatID, filename, contentType, r.Body) if err != nil { h.fail(w, r, err) return } writeJSON(w, http.StatusCreated, toAttachmentResponse(attachment)) } func (h *Handler) GetAttachment(w http.ResponseWriter, r *http.Request) { id, err := attachmentIDParam(r) if err != nil { h.fail(w, r, err) return } attachment, err := h.attachments.Get(r.Context(), actor(r), id) if err != nil { h.fail(w, r, err) return } writeJSON(w, http.StatusOK, toAttachmentResponse(attachment)) } func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) { id, err := attachmentIDParam(r) if err != nil { h.fail(w, r, err) return } attachment, content, err := h.attachments.Open(r.Context(), actor(r), id, r.URL.Query().Get("variant")) if err != nil { h.fail(w, r, err) return } defer content.Close() w.Header().Set("Content-Type", attachment.ContentType) w.Header().Set("Content-Length", strconv.FormatInt(attachment.SizeBytes, 10)) w.WriteHeader(http.StatusOK) if _, err := io.Copy(w, content); err != nil { h.log.Error("attachment download interrupted", "request_id", w.Header().Get(headerRequestID), "err", err) } } func attachmentIDParam(r *http.Request) (uuid.UUID, error) { id, ok := parseUUID(chi.URLParam(r, "attachment_id")) if !ok { return uuid.UUID{}, badRequest("attachment_id must be a UUID") } return id, nil }