-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
87 lines (73 loc) · 1.71 KB
/
handlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"bufio"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"golang.org/x/exp/slog"
)
// Handlers groups a bunch of HTTP handlers.
type Handlers struct {
uploader *Uploader
tmpDir string
}
// UploadResponse ...
type UploadResponse struct {
Root string `json:"root"`
Shard string `json:"shard"`
}
// Health is a health checker.
func (h *Handlers) Health(rw http.ResponseWriter, _ *http.Request) {
rw.WriteHeader(http.StatusOK)
}
// Upload handles POST /api/v1/upload.
func (h *Handlers) Upload(rw http.ResponseWriter, r *http.Request) {
reader, err := r.MultipartReader()
if err != nil {
http.Error(rw, err.Error(), http.StatusBadRequest)
return
}
// parse file field
p, err := reader.NextPart()
if err != nil && err != io.EOF {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if p.FormName() != "file" {
http.Error(rw, "file is expected", http.StatusBadRequest)
return
}
buf := bufio.NewReader(p)
result, err := h.uploader.Upload(r.Context(), buf)
if err != nil {
slog.Error("file upload", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
response := &UploadResponse{
Root: result.Root.String(),
Shard: result.Shard.String(),
}
bytes, err := json.Marshal(response)
if err != nil {
slog.Error("json marshaling", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
_, _ = rw.Write(bytes)
}
func initHandlers(cfg *config) (*Handlers, error) {
proof, err := hex.DecodeString(cfg.Proof)
if err != nil {
return nil, err
}
uploader, err := NewUploader(cfg.SpaceID, cfg.PrivateKey, proof, cfg.TmpDir)
if err != nil {
return nil, err
}
return &Handlers{
uploader: uploader,
tmpDir: cfg.TmpDir,
}, nil
}