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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
|
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"text/template"
"time"
"github.com/google/uuid"
jsonschema "github.com/santhosh-tekuri/jsonschema/v5"
)
type HTTPError struct {
code int
root error
}
func (e *HTTPError) Error() string {
msg := http.StatusText(e.code)
if e.root != nil {
msg += ": " + e.root.Error()
}
return msg
}
type SiteHandler struct {
name string
path string
schema *jsonschema.Schema
referer_pat *regexp.Regexp
redirect_tpl *template.Template
}
type SiteConfig struct {
RefererPattern string
RedirectTemplate string
}
type TemplateParams struct {
Id string
Key string
}
func NewSiteHandler(site_name string, site_path string) (*SiteHandler, error) {
schema, err := jsonschema.Compile(filepath.Join(site_path, ".schema.json"))
if err != nil {
return nil, err
}
var cfg SiteConfig
cfg_data, err := os.ReadFile(filepath.Join(site_path, ".config.json"))
if err != nil {
return nil, err
}
if err := json.Unmarshal(cfg_data, &cfg); err != nil {
return nil, err
}
referer := regexp.MustCompile(cfg.RefererPattern)
template := template.Must(template.New(site_name + "_redirect").Parse(cfg.RedirectTemplate))
return &SiteHandler{site_name, site_path, schema, referer, template}, nil
}
func NewMeta() (map[string]interface{}, error) {
id, err := uuid.NewUUID()
if err != nil {
return nil, err
}
key, err := uuid.NewRandom()
if err != nil {
return nil, err
}
now := time.Now().UTC().String()
data := make(map[string]interface{})
data["id"] = id.String()
data["key"] = key.String()
data["submitted"] = now
return data, nil
}
func processValue(typ string, value string) interface{} {
switch typ {
case "null":
if value == "" {
return nil
}
case "boolean":
if value == "true" || value == "on" {
return true
} else if value == "false" || value == "off" {
return false
}
case "number":
val, err := strconv.ParseFloat(value, 64)
if err == nil {
return val
}
case "integer":
val, err := strconv.Atoi(value)
if err == nil {
return val
}
}
return value
}
func (h *SiteHandler) collectData(r *http.Request) (map[string]interface{}, error) {
content_type := r.Header.Get("Content-Type")
var err error
if content_type == "application/x-www-form-urlencoded" {
err = r.ParseForm()
} else if content_type == "multipart/form-data" {
err = r.ParseMultipartForm(1 * 1024 * 1024)
}
if err != nil {
return nil, &HTTPError{http.StatusBadRequest, err}
}
data := make(map[string]interface{})
for key, values := range r.PostForm {
if key == "_key" {
continue
}
key_schema, ok := h.schema.Properties[key]
val_type := ""
if ok && key_schema.Types[0] == "array" {
if key_schema.Items2020 != nil {
val_type = key_schema.Items2020.Types[0]
}
} else if ok {
val_type = key_schema.Types[0]
}
if ok && key_schema.Types[0] != "array" && len(values) == 1 {
data[key] = processValue(val_type, values[0])
} else {
tmp := make([]interface{}, len(values))
for i := range values {
tmp[i] = processValue(val_type, values[i])
}
data[key] = tmp
}
}
return data, nil
}
func (h *SiteHandler) handlePOST(w http.ResponseWriter, r *http.Request, meta map[string]interface{}) error {
data, err := h.collectData(r)
if err != nil {
return err
}
if err := h.schema.Validate(data); err != nil {
log.Printf("Validation Error %s", err)
return &HTTPError{http.StatusNotAcceptable, nil}
}
if meta == nil {
meta, err = NewMeta()
if err != nil {
return err
}
} else {
meta["updated"] = time.Now().UTC().String()
}
data["$meta"] = meta
raw_data, err := json.Marshal(data)
if err != nil {
return err
}
id, key := meta["id"].(string), meta["key"].(string)
if err := os.WriteFile(
filepath.Join(h.path, id + ".json"),
append(raw_data, '\n'),
0644,
); err != nil {
return err
}
log.Printf("POST %s", meta["id"])
var redirect_buf bytes.Buffer
h.redirect_tpl.Execute(&redirect_buf, TemplateParams{id, key})
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Location", redirect_buf.String())
w.WriteHeader(http.StatusSeeOther)
w.Write(raw_data)
return nil
}
func (h *SiteHandler) handle(w http.ResponseWriter, r *http.Request) error {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 3 || parts[1] != h.name {
return &HTTPError{http.StatusInternalServerError, nil}
}
if !h.referer_pat.MatchString(r.Header.Get("Referer")) {
return &HTTPError{http.StatusUnauthorized, nil}
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "*")
id := parts[2]
if id == "" {
if r.Method != "POST" {
return &HTTPError{http.StatusMethodNotAllowed, nil}
}
return h.handlePOST(w, r, nil)
}
var data map[string]interface{}
raw_data, err := os.ReadFile(filepath.Join(h.path, id+".json"))
if err != nil {
return &HTTPError{http.StatusNotFound, nil}
}
if err := json.Unmarshal(raw_data, &data); err != nil {
return err
}
meta := data["$meta"].(map[string]interface{})
key := r.FormValue("_key")
if meta["key"] != key {
return &HTTPError{http.StatusUnauthorized, nil}
}
if r.Method == "POST" {
return h.handlePOST(w, r, meta)
} else if r.Method == "GET" {
w.Header().Set("Content-Type", "application/json")
w.Write(raw_data)
return nil
}
return &HTTPError{http.StatusMethodNotAllowed, nil}
}
func (h *SiteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := h.handle(w, r)
if err != nil {
var code int
switch e := err.(type) {
case *HTTPError:
code = e.code
if e.root != nil {
log.Printf("Error %s: ", err.Error(), e.root)
}
default:
code = http.StatusInternalServerError
log.Printf("Error: ", err)
}
http.Error(w, http.StatusText(code), code)
}
}
func main() {
sites, err := filepath.Glob(os.Args[1] + "/*")
if err != nil {
log.Fatalf("Error locating sites: %#v", err)
}
for _, site_path := range sites {
site_name := filepath.Base(site_path)
log.Printf("loading site %s", site_name)
handler, err := NewSiteHandler(site_name, site_path)
if err != nil {
log.Fatalf("NewSiteHandler %s: ", site_path, err)
}
http.Handle("/"+site_name+"/", handler)
}
log.Printf("ready, listening on :3000")
err = http.ListenAndServe(":3000", nil) // setting listening port
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
|