-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.go
107 lines (92 loc) · 2.15 KB
/
server.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"sync"
"time"
"github.com/go-chi/chi"
)
// Blob is a byte slice
type Blob []byte
const (
minExpires = 1
maxExpires = 60000
)
var (
defaultExpires = 15 * time.Second
expireAfterRangeErr = fmt.Sprintf("X-Delete-After must be within (%d, %d)", minExpires, maxExpires)
)
// Server contains the server's state
type Server struct {
Cache map[string]Blob
lock sync.RWMutex
}
// Upload an image to the cache
func (server *Server) Upload(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "key")
data, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
if len(data) == 0 {
http.Error(w, "payload was empty", http.StatusBadRequest)
return
}
server.lock.Lock()
server.Cache[id] = Blob(data)
server.lock.Unlock()
w.WriteHeader(http.StatusNoContent)
expire := defaultExpires
if e := r.Header.Get("X-Delete-After"); e != "" {
d, err := strconv.ParseInt(e, 10, 64)
if err != nil {
http.Error(w, "X-Delete-After should be an integer", http.StatusBadRequest)
return
}
if d < minExpires || d > maxExpires {
http.Error(w, expireAfterRangeErr, http.StatusBadRequest)
return
}
expire = time.Duration(d) * time.Millisecond
}
go func() {
time.Sleep(expire)
server.lock.Lock()
delete(server.Cache, id)
server.lock.Unlock()
}()
}
// Get an image from the cache
func (server *Server) Get(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "key")
server.lock.RLock()
data, ok := server.Cache[id]
server.lock.RUnlock()
if !ok {
http.Error(w, "object not found", http.StatusNotFound)
return
}
_, err := w.Write(data)
if err != nil {
panic(err)
}
}
// List all the objects from the cache in JSON
func (server *Server) List(w http.ResponseWriter, r *http.Request) {
data := make(map[string]string)
i := 0
server.lock.RLock()
for key := range server.Cache {
data[strconv.Itoa(i)] = key
i++
}
server.lock.RUnlock()
out, _ := json.Marshal(data)
_, err := w.Write(out)
if err != nil {
panic(err)
}
}