This repository has been archived by the owner on Jan 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
paste.go
77 lines (64 loc) · 1.55 KB
/
paste.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
package handler
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/jaevor/go-nanoid"
"github.com/pixec/triangle/store"
)
type Paste struct {
logger *slog.Logger
store store.Store
}
func NewPaste(l *slog.Logger, s store.Store) *Paste {
return &Paste{
logger: l,
store: s,
}
}
func (h *Paste) Paste(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "paste")
if id == "" {
w.WriteHeader(http.StatusNotFound)
return
}
p, err := h.store.Paste(id)
if err != nil {
if errors.Is(err, store.ErrPasteNotFound) {
w.WriteHeader(http.StatusNotFound)
return
}
h.logger.Error("could not fetch paste from store", slog.Any("error", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(p)
}
func (h *Paste) Insert(w http.ResponseWriter, r *http.Request) {
var data struct {
Content string `json:"content"`
}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if len(data.Content) < 8 || len(data.Content) > 1000 {
w.WriteHeader(http.StatusBadRequest)
return
}
id, err := nanoid.Standard(14)
if err != nil {
h.logger.Error("could not generate paste identifier", slog.Any("error", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
p, err := h.store.InsertPaste(id(), data.Content)
if err != nil {
h.logger.Error("could not insert paste to store", slog.Any("error", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(p)
}