-
Notifications
You must be signed in to change notification settings - Fork 0
/
share.go
86 lines (69 loc) · 2.03 KB
/
share.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
package api
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"github.com/go-chi/chi"
"github.com/ap4y/cloud/internal/httputil"
"github.com/ap4y/cloud/share"
)
type shareHandler struct {
store share.Store
}
func (sh shareHandler) listShares(w http.ResponseWriter, req *http.Request) {
shares, err := sh.store.All()
if err != nil {
httputil.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
httputil.Respond(w, shares)
}
func (sh shareHandler) getShare(w http.ResponseWriter, req *http.Request) {
slug := chi.URLParam(req, "slug")
if slug == "" {
httputil.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
share, err := sh.store.Get(slug)
if err != nil {
httputil.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
httputil.Respond(w, share)
}
func (sh shareHandler) createShare(w http.ResponseWriter, req *http.Request) {
var share *share.Share
if err := json.NewDecoder(req.Body).Decode(&share); err != nil {
httputil.Error(w, fmt.Sprintf("Failed to decode json: %s", err), http.StatusBadRequest)
return
}
slug := make([]byte, 10)
if _, err := rand.Read(slug); err != nil {
httputil.Error(w, fmt.Sprintf("Failed to generate slug: %s", err), http.StatusBadRequest)
return
}
share.Slug = base64.URLEncoding.EncodeToString(slug)
if !share.IsValid() {
httputil.Error(w, "Invalid share", http.StatusUnprocessableEntity)
return
}
if err := sh.store.Save(share); err != nil {
httputil.Error(w, fmt.Sprintf("Failed to save: %s", err), http.StatusBadRequest)
return
}
httputil.Respond(w, share)
}
func (sh shareHandler) removeShare(w http.ResponseWriter, req *http.Request) {
slug := chi.URLParam(req, "slug")
if slug == "" {
httputil.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
if err := sh.store.Remove(slug); err != nil {
httputil.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
httputil.Respond(w, map[string]string{})
}