-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
218 lines (187 loc) · 5.71 KB
/
api.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"time"
"github.com/0x4c6565/p.lee.io/pkg/model"
"github.com/0x4c6565/p.lee.io/pkg/storage"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
)
type pasteRequest struct {
Expires int64 `json:"expires"`
Syntax string `json:"syntax"`
Content string `json:"content"`
}
type pasteResponse struct {
Expires int64 `json:"expires"`
Syntax string `json:"syntax"`
Content string `json:"content"`
Burnt bool `json:"burnt"`
}
type uuidResponse struct {
ID string `json:"id"`
}
type syntaxResponse struct {
Label string `json:"label"`
Syntax string `json:"syntax"`
Default bool `json:"default,omitempty"`
Aliases []string `json:"aliases,omitempty"`
}
type expiresResponse struct {
Label string `json:"label"`
Default bool `json:"default,omitempty"`
Expires int `json:"expires"`
}
type apiError struct {
Err error
Code int
}
type API struct {
storage storage.Storage
config *Config
router *mux.Router
}
func NewAPI(storage storage.Storage, config *Config) *API {
return &API{
storage: storage,
config: config,
}
}
func (h *API) Start(ctx context.Context) error {
log.Info().Msg("Starting API")
h.router = mux.NewRouter()
h.router.HandleFunc(`/api/v1/paste/{uuid:\S+}`, h.HandleGetPaste).Methods("GET")
h.router.HandleFunc("/api/v1/paste", h.HandleCreatePaste).Methods("POST")
h.router.HandleFunc(`/api/v1/syntax`, h.HandleGetSyntax).Methods("GET")
h.router.HandleFunc(`/api/v1/expires`, h.HandleGetExpires).Methods("GET")
// h.router.HandleFunc(`/raw/{uuid:\S+}`, h.HandleGetPasteRaw).Methods("GET")
h.router.PathPrefix(`/raw/{uuid:[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}}`).Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/raw.html")
})).Methods("GET")
h.router.PathPrefix(`/{uuid:[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}}`).Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/index.html")
})).Methods("GET")
fs := http.FileServer(http.Dir("./static"))
h.router.PathPrefix("/").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fs.ServeHTTP(w, r)
})).Methods("GET")
loggedRouter := handlers.LoggingHandler(os.Stdout, h.router)
srv := &http.Server{
Addr: ":8080",
Handler: loggedRouter,
}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal().Err(err).Msgf("HTTP listener failure")
}
}()
log.Info().Msg("API started")
<-ctx.Done()
log.Info().Msg("API shutting down..")
if err := srv.Shutdown(ctx); err != nil {
return fmt.Errorf("HTTP listener shutdown failed: %s", err)
}
log.Info().Msg("API stopped")
return nil
}
func (h *API) HandleGetPaste(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
paste, err := h.storage.Get(context.Background(), vars["uuid"])
if err != nil {
var notFoundErr *storage.NotFoundError
if errors.As(err, ¬FoundErr) {
h.handleJSONResponse(w, http.StatusNotFound, "Cannot find paste")
return
}
log.Error().Msgf("Error retrieving paste: %s", err.Error())
h.handleJSONResponse(w, http.StatusInternalServerError, nil)
return
}
burnt := false
if paste.Expires == model.PASTE_EXPIRES_BURN {
err = h.storage.Delete(context.Background(), paste.ID)
if err != nil {
log.Error().Msgf("Error burning paste: %s", err.Error())
h.handleJSONResponse(w, http.StatusInternalServerError, nil)
return
}
burnt = true
}
h.handleJSONResponse(w, http.StatusOK, &pasteResponse{
Expires: paste.Expires,
Syntax: paste.Syntax,
Content: paste.Content,
Burnt: burnt,
})
}
func (h *API) HandleCreatePaste(w http.ResponseWriter, r *http.Request) {
var req pasteRequest
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&req)
if err != nil {
h.handleJSONResponse(w, http.StatusBadRequest, fmt.Sprintf("Unable to decode JSON payload: %s", err))
return
}
defer r.Body.Close()
syntaxExists, syntax := h.config.ResolveSyntax(req.Syntax)
if !syntaxExists {
h.handleJSONResponse(w, http.StatusBadRequest, "Invalid syntax")
return
}
id, err := h.storage.Add(context.Background(), model.Paste{
Expires: req.Expires,
Timestamp: time.Now().Unix(),
Syntax: syntax.Syntax,
Content: req.Content,
})
if err != nil {
log.Error().Msgf("Error storing paste: %s", err.Error())
h.handleJSONResponse(w, http.StatusInternalServerError, nil)
return
}
h.handleJSONResponse(w, http.StatusOK, &uuidResponse{
ID: id,
})
}
func (h *API) HandleGetSyntax(w http.ResponseWriter, r *http.Request) {
var resp []syntaxResponse
for _, syntax := range h.config.Syntax {
resp = append(resp, syntaxResponse{
Label: syntax.Label,
Syntax: syntax.Syntax,
Default: syntax.Label == h.config.SyntaxDefault,
Aliases: syntax.Aliases,
})
}
h.handleJSONResponse(w, http.StatusOK, resp)
}
func (h *API) HandleGetExpires(w http.ResponseWriter, r *http.Request) {
var resp []expiresResponse
resp = append(resp, expiresResponse{
Label: "Never",
Expires: model.PASTE_EXPIRES_NEVER,
})
resp = append(resp, expiresResponse{
Label: "Burn after reading",
Expires: model.PASTE_EXPIRES_BURN,
})
for _, expires := range h.config.Expires {
resp = append(resp, expiresResponse{
Label: expires.Label,
Default: expires.Label == h.config.ExpiresDefault,
Expires: expires.Expires,
})
}
h.handleJSONResponse(w, http.StatusOK, resp)
}
func (h *API) handleJSONResponse(w http.ResponseWriter, statusCode int, content interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(content)
}