返回 DeepSeek-Reasonix
attachment_upload.go
根目录 / desktop / attachment_upload.go
1 package main
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "net/http"
8
9 "reasonix/internal/config"
10 "reasonix/internal/control"
11 )
12
13 const attachmentUploadPath = "/__reasonix_attachment_upload"
14
15 func (a *App) attachmentUploadMiddleware() func(http.Handler) http.Handler {
16 return func(next http.Handler) http.Handler {
17 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
18 if r.URL.Path != attachmentUploadPath {
19 next.ServeHTTP(w, r)
20 return
21 }
22 w.Header().Set("Cache-Control", "no-store")
23 if r.Method != http.MethodPost {
24 w.Header().Set("Allow", http.MethodPost)
25 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
26 return
27 }
28 if r.Header.Get("Content-Type") != "application/octet-stream" {
29 http.Error(w, "unsupported upload type", http.StatusUnsupportedMediaType)
30 return
31 }
32 target, err := a.attachmentTargetToken(r.URL.Query().Get("target"))
33 if err != nil {
34 http.Error(w, "attachment target is unavailable", http.StatusConflict)
35 return
36 }
37 limit, err := config.LoadAttachmentStreamLimit()
38 if err != nil {
39 http.Error(w, "attachment upload configuration could not be read", http.StatusInternalServerError)
40 return
41 }
42 ctx, cancel := context.WithCancel(r.Context())
43 defer cancel()
44 stop := context.AfterFunc(a.attachmentOperationContext(target), func() { cancel(); _ = r.Body.Close() })
45 defer stop()
46 rel, err := control.SaveAttachmentStreamInRoot(ctx, target.root, r.URL.Query().Get("name"), r.Body, limit)
47 rel, err = a.finishAttachmentWrite(target, rel, err)
48 if err != nil {
49 if !a.attachmentTargetCurrent(target) {
50 http.Error(w, "attachment upload could not be saved", http.StatusConflict)
51 return
52 }
53 var limitErr *control.AttachmentStreamLimitError
54 if errors.As(err, &limitErr) {
55 w.Header().Set("Content-Type", "application/json")
56 w.WriteHeader(http.StatusRequestEntityTooLarge)
57 _ = json.NewEncoder(w).Encode(struct {
58 Code string `json:"code"`
59 Message string `json:"message"`
60 LimitBytes int64 `json:"limit_bytes"`
61 LimitSource string `json:"limit_source"`
62 }{"attachment.too_large", limitErr.Error(), limitErr.LimitBytes, limitErr.LimitSource})
63 return
64 }
65 http.Error(w, "attachment upload could not be saved", http.StatusInternalServerError)
66 return
67 }
68 w.Header().Set("Content-Type", "application/json")
69 _ = json.NewEncoder(w).Encode(struct {
70 Path string `json:"path"`
71 }{Path: rel})
72 })
73 }
74 }
75
75 lines GO