forked from folbricht/desync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpindexhandler.go
95 lines (84 loc) · 2.17 KB
/
httpindexhandler.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
package desync
import (
"bytes"
"fmt"
"net/http"
"os"
"path"
)
// HTTPIndexHandler is the HTTP handler for index stores.
type HTTPIndexHandler struct {
HTTPHandlerBase
s IndexStore
}
// NewHTTPIndexHandler initializes an HTTP index store handler
func NewHTTPIndexHandler(s IndexStore, writable bool) http.Handler {
return HTTPIndexHandler{HTTPHandlerBase{"index", writable}, s}
}
func (h HTTPIndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
indexName := path.Base(r.URL.Path)
switch r.Method {
case "GET":
h.get(indexName, w)
case "HEAD":
h.head(indexName, w)
case "PUT":
h.put(indexName, w, r)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("only GET, PUT and HEAD are supported"))
}
}
func (h HTTPIndexHandler) get(indexName string, w http.ResponseWriter) {
idx, err := h.s.GetIndex(indexName)
if err != nil {
if os.IsNotExist(err) {
w.WriteHeader(http.StatusNotFound)
} else {
w.WriteHeader(http.StatusBadRequest)
}
fmt.Fprintln(w, err)
return
}
b := new(bytes.Buffer)
_, err = idx.WriteTo(b)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
h.HTTPHandlerBase.get(indexName, b.Bytes(), err, w)
}
func (h HTTPIndexHandler) head(indexName string, w http.ResponseWriter) {
_, err := h.s.GetIndexReader(indexName)
if err != nil {
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusNotFound)
}
func (h HTTPIndexHandler) put(indexName string, w http.ResponseWriter, r *http.Request) {
err := h.HTTPHandlerBase.validateWritable(h.s.String(), w, r)
if err != nil {
return
}
// The upstream store needs to support writing as well
s, ok := h.s.(IndexWriteStore)
if !ok {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "upstream index store '%s' does not support writing\n", h.s)
return
}
// Read the chunk into memory
idx, err := IndexFromReader(r.Body)
if err != nil {
http.Error(w, "invalid index: "+err.Error(), http.StatusUnsupportedMediaType)
return
}
// Store it upstream
if err := s.StoreIndex(indexName, idx); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, err)
return
}
w.WriteHeader(http.StatusOK)
}