forked from folbricht/desync
/
httphandler.go
113 lines (99 loc) · 2.55 KB
/
httphandler.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package desync
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
type HTTPHandler struct {
HTTPHandlerBase
s Store
}
func NewHTTPHandler(s Store, writable bool) http.Handler {
return HTTPHandler{HTTPHandlerBase{"chunk", writable}, s}
}
func (h HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sid := strings.TrimSuffix(filepath.Base(r.URL.Path), ".cacnk")
// We only really need the ID, but to maintain compatibility with stores
// that are simply shared with HTTP, we expect /prefix/chunkID. Make sure
// the prefix does match the first characters of the ID.
if r.URL.Path != filepath.Join(string(os.PathSeparator), sid[0:4], sid+".cacnk") {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("expected /prefix/chunkid.cacnk"))
return
}
switch r.Method {
case "GET":
h.get(sid, w)
case "HEAD":
h.head(sid, w)
case "PUT":
h.put(sid, w, r)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("only GET, PUT and HEAD are supported"))
}
}
func (h HTTPHandler) parseChunkId(sid string, w http.ResponseWriter) (ChunkID, error) {
// Parse the ID and verify the format
cid, err := ChunkIDFromString(sid)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("invalid chunk id"))
return ChunkID{}, err
}
return cid, err
}
func (h HTTPHandler) get(sid string, w http.ResponseWriter) {
cid, err := h.parseChunkId(sid, w)
if err != nil {
return
}
b, err := h.s.GetChunk(cid)
h.HTTPHandlerBase.get(sid, b, err, w)
}
func (h HTTPHandler) head(sid string, w http.ResponseWriter) {
cid, err := h.parseChunkId(sid, w)
if err != nil {
return
}
if h.s.HasChunk(cid) {
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusNotFound)
}
func (h HTTPHandler) put(sid string, w http.ResponseWriter, r *http.Request) {
err := h.HTTPHandlerBase.validateWritable(h.s.String(), w, r)
if err != nil {
return
}
cid, err := h.parseChunkId(sid, w)
if err != nil {
return
}
// The upstream store needs to support writing as well
s, ok := h.s.(WriteStore)
if !ok {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "upstream chunk store '%s' does not support writing\n", h.s)
return
}
// Read the chunk into memory
b := new(bytes.Buffer)
if _, err := io.Copy(b, r.Body); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, err)
return
}
// Store it upstream
if err := s.StoreChunk(cid, b.Bytes()); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, err)
return
}
w.WriteHeader(http.StatusOK)
}