-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathresponse.go
More file actions
209 lines (171 loc) · 3.81 KB
/
Copy pathresponse.go
File metadata and controls
209 lines (171 loc) · 3.81 KB
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
package mitch
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strconv"
"github.com/gorilla/mux"
)
var DEBUG2 = os.Getenv("MITCH_DEBUG") == "2"
var DEBUG = DEBUG2 || os.Getenv("MITCH_DEBUG") == "1"
type response struct {
s *server
w http.ResponseWriter
req *http.Request
status int
store *Store
currentUser *User
}
type Any map[string]any
type APIError struct {
status int
messages []string
}
func Error(status int, messages ...string) APIError {
return APIError{
status: status,
messages: messages,
}
}
func Throw(status int, messages ...string) APIError {
panic(Error(status, messages...))
}
func (ae APIError) Error() string {
return fmt.Sprintf("api error (%d): %v", ae.status, ae.messages)
}
func (r *response) WriteError(status int, errors ...string) {
r.status = status
payload := map[string]any{
"errors": errors,
}
r.WriteJSON(payload)
}
func (r *response) WriteEmpty() {
r.status = 204
r.WriteHeader()
}
func (r *response) WriteJSON(payload any) {
bs, err := json.MarshalIndent(payload, "", " ")
if err != nil {
panic(err)
}
r.Header().Set("content-type", "application/json")
r.WriteHeader()
debugf("Replying with JSON payload: %s", string(bs))
_, _ = r.w.Write(bs)
}
func (r *response) Header() http.Header {
return r.w.Header()
}
func (r *response) WriteHeader() {
status := r.status
if r.status == 0 {
status = 200
}
r.w.WriteHeader(status)
}
type RespondToMap map[string]func()
var (
validRespondToMethods = map[string]bool{
"GET": true,
"POST": true,
}
)
func (r *response) RespondTo(m RespondToMap) {
for k := range m {
if !validRespondToMethods[k] {
Throw(500, fmt.Sprintf("handler is trying to handle invalid method %s", k))
}
}
if h, ok := m[r.req.Method]; ok {
h()
} else {
Throw(400, "invalid method")
}
}
func (r *response) Int64Var(name string) int64 {
res, err := strconv.ParseInt(r.Var(name), 10, 64)
must(err)
return res
}
func (r *response) Var(name string) string {
return mux.Vars(r.req)[name]
}
func (r *response) CheckAPIKey() {
keyString := r.req.Header.Get("Authorization")
if keyString == "" {
keyString = r.req.URL.Query().Get("api_key")
}
if keyString == "" {
Throw(401, "authentication required")
}
apiKey := r.s.store.FindAPIKeysByKey(keyString)
if apiKey == nil {
Throw(403, "unauthorized")
}
r.currentUser = r.s.store.FindUser(apiKey.UserID)
if r.currentUser == nil {
Throw(500, "api key has no user")
}
}
func (r *response) Params() url.Values {
return r.req.Form
}
func (r *response) Param(key string) string {
return r.req.Form.Get(key)
}
func (r *response) Int64Param(key string) int64 {
res, err := strconv.ParseInt(r.Param(key), 10, 64)
must(err)
return res
}
func (r *response) AssertAuthorization(authorized bool) {
if !authorized {
Throw(403, "forbidden")
}
}
func (r *response) RedirectTo(url string) {
r.Header().Set("Location", url)
r.status = 302
r.WriteHeader()
}
func (r *response) FindGame(gameID int64) *Game {
game := r.store.FindGame(gameID)
if game == nil {
Throw(404, "game not found")
}
return game
}
func (r *response) FindUpload(uploadID int64) *Upload {
upload := r.store.FindUpload(uploadID)
if upload == nil {
Throw(404, "upload not found")
}
return upload
}
func (r *response) FindBuild(buildID int64) *Build {
build := r.store.FindBuild(buildID)
if build == nil {
Throw(404, "build not found")
}
return build
}
func (r *response) makeURL(format string, args ...any) string {
path := fmt.Sprintf(format, args...)
url := fmt.Sprintf("http://%s%s", r.s.Address().String(), path)
return url
}
type cdnAsset interface {
CDNPath() string
}
func (r *response) ServeCDNAsset(ass cdnAsset) {
r.RedirectTo(r.makeURL("/@cdn%s", ass.CDNPath()))
}
func debugf(s string, a ...any) {
if DEBUG2 {
log.Printf("[mitch] %s", fmt.Sprintf(s, a...))
}
}