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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
|
package forge
import (
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
var fullOID = regexp.MustCompile(`^[0-9a-f]{40}$`)
func (s *Server) gistIndex(w http.ResponseWriter, r *http.Request) {
user := s.current(r)
gists, err := s.store.Gists(0, false, 50)
if err != nil {
s.fail(w, r, 500, err.Error())
return
}
s.render(w, r, "gists", page{Title: "Gists", User: user, Data: map[string]any{"Items": s.gistItems(gists)}})
}
func (s *Server) userGists(w http.ResponseWriter, r *http.Request, owner User, user *User) {
own := user != nil && user.ID == owner.ID
gists, err := s.store.Gists(owner.ID, own, 200)
if err != nil {
s.fail(w, r, 500, err.Error())
return
}
data := map[string]any{"Owner": owner, "Items": s.gistItems(gists), "Own": own, "Count": len(gists)}
if r.URL.Query().Get("tab") == "starred" {
starred, _ := s.store.StarredGists(owner.ID)
data["Items"], data["Starred"] = s.gistItems(starred), true
}
s.render(w, r, "gists", page{Title: "~" + owner.Name + " gists", User: user, Data: data})
}
func formFiles(r *http.Request) []gistFile {
names, contents, origs := r.PostForm["name"], r.PostForm["content"], r.PostForm["orig"]
var files []gistFile
for i := range min(len(contents), gistFormFiles) {
f := gistFile{Content: strings.ReplaceAll(contents[i], "\r\n", "\n")}
if i < len(names) {
f.Name = strings.TrimSpace(names[i])
}
if i < len(origs) {
f.Orig = origs[i]
}
files = append(files, f)
}
return files
}
func (s *Server) newGistForm(w http.ResponseWriter, r *http.Request) {
u := s.require(w, r)
if u == nil {
return
}
s.render(w, r, "gistform", page{Title: "New gist", User: u, Data: map[string]any{"Files": []gistFile{{}}, "Action": "/gists"}})
}
func (s *Server) postGist(w http.ResponseWriter, r *http.Request) {
u := s.require(w, r)
if u == nil {
return
}
r.Body = http.MaxBytesReader(w, r.Body, 8<<20)
if err := r.ParseForm(); err != nil {
s.fail(w, r, 400, "The gist is too large")
return
}
files := formFiles(r)
data := map[string]any{"Files": files, "Action": "/gists", "Description": r.FormValue("description"), "Secret": r.FormValue("visibility") == "secret"}
if r.FormValue("action") == "add" {
data["Files"] = append(files, gistFile{})
s.render(w, r, "gistform", page{Title: "New gist", User: u, Data: data})
return
}
gist, err := s.createGist(*u, r.FormValue("description"), r.FormValue("visibility") == "secret", files)
if err != nil {
w.WriteHeader(400)
s.render(w, r, "gistform", page{Title: "New gist", User: u, Error: err.Error(), Data: data})
return
}
http.Redirect(w, r, "/gist/"+gist.ID, http.StatusSeeOther)
}
func (s *Server) gistRoute(w http.ResponseWriter, r *http.Request) {
id, sub, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/gist/"), "/")
id = strings.TrimSuffix(id, ".git")
if !gistID.MatchString(id) {
s.fail(w, r, 404, "No such gist")
return
}
gist, err := s.store.Gist(id)
if err != nil {
if isSmart(r, sub) {
http.Error(w, "gist not found", 404)
return
}
s.fail(w, r, 404, "No such gist")
return
}
if isSmart(r, sub) {
s.gistSmart(w, r, gist, sub)
return
}
user := s.current(r)
back := "/gist/" + gist.ID
switch {
case sub == "" && r.Method == "GET":
s.gistPage(w, r, gist, user)
case sub == "revisions" && r.Method == "GET":
s.gistRevisions(w, r, gist, user)
case sub == "edit":
s.editGist(w, r, gist, user)
case strings.HasPrefix(sub, "raw/") && r.Method == "GET":
http.Redirect(w, r, "https://"+s.rawHost()+"/raw/"+gist.ID+"/"+escapePath(strings.TrimPrefix(sub, "raw/")), http.StatusFound)
case r.Method != "POST":
s.fail(w, r, 404, "Page not found")
case user == nil:
http.Redirect(w, r, "/login", http.StatusSeeOther)
case sub == "star":
s.store.StarGist(user.ID, gist.ID, !s.store.GistStarred(user.ID, gist.ID))
http.Redirect(w, r, back, http.StatusSeeOther)
case sub == "fork":
if user.ID == gist.Owner.ID {
s.fail(w, r, 400, "You already own this gist")
return
}
fork, err := s.forkGist(*user, gist)
if err != nil {
s.fail(w, r, 400, err.Error())
return
}
http.Redirect(w, r, "/gist/"+fork.ID, http.StatusSeeOther)
case sub == "delete":
if user.ID != gist.Owner.ID && !s.store.IsAdmin(user.ID) {
s.fail(w, r, 403, "Only the owner can delete this gist")
return
}
s.store.DeleteGist(gist.ID)
os.RemoveAll(s.gistGit(gist).Dir)
s.store.CloseReports("gist", gist.Owner.Name+"/"+gist.ID, "resolved", user.ID)
http.Redirect(w, r, "/~"+gist.Owner.Name+"/gists", http.StatusSeeOther)
case sub == "comment":
if s.store.Blocked(gist.Owner.ID, user.ID) {
s.fail(w, r, 403, "You cannot comment here")
return
}
if err := s.store.AddGistComment(gist.ID, user.ID, r.FormValue("body")); err != nil {
http.Redirect(w, r, back+"?error="+url.QueryEscape(err.Error())+"#comments", http.StatusSeeOther)
return
}
http.Redirect(w, r, back+"#comments", http.StatusSeeOther)
case strings.HasPrefix(sub, "comment/") && strings.HasSuffix(sub, "/delete"):
cid, err := strconv.ParseInt(strings.TrimSuffix(strings.TrimPrefix(sub, "comment/"), "/delete"), 10, 64)
author, ok := s.store.GistCommentAuthor(gist.ID, cid)
if err != nil || !ok {
s.fail(w, r, 404, "No such comment")
return
}
if author != user.ID && gist.Owner.ID != user.ID && !s.store.IsAdmin(user.ID) {
s.fail(w, r, 403, "You cannot delete that comment")
return
}
s.store.DeleteGistComment(cid)
http.Redirect(w, r, back+"#comments", http.StatusSeeOther)
default:
s.fail(w, r, 404, "Page not found")
}
}
func (s *Server) gistPage(w http.ResponseWriter, r *http.Request, gist Gist, user *User) {
head := s.gistHead(gist)
commit := head
if rev := r.URL.Query().Get("rev"); fullOID.MatchString(rev) {
if c, err := s.gistGit(gist).Resolve(rev + "^{commit}"); err == nil {
commit = c
}
}
views := s.gistViews(gist, commit, 0)
var files []string
for _, v := range views {
files = append(files, v.Name)
}
comments := s.store.GistComments(gist.ID)
rendered := make([]map[string]any, len(comments))
math := false
for i, c := range comments {
body := s.renderMarkdown([]byte(c.Body))
math = math || hasMath(body)
rendered[i] = map[string]any{"Comment": c, "Body": body}
}
for _, v := range views {
math = math || hasMath(v.Markdown)
}
data := map[string]any{
"Gist": gist, "Files": views, "Title": gist.Title(files), "Commit": commit, "Head": head, "Old": commit != head,
"Comments": rendered, "Owner": user != nil && user.ID == gist.Owner.ID,
"Admin": user != nil && s.store.IsAdmin(user.ID), "Starred": user != nil && s.store.GistStarred(user.ID, gist.ID),
"Clone": "https://" + s.host + "/gist/" + gist.ID + ".git", "SSH": s.sshUser + "@" + s.sshHost + ":gist/" + gist.ID + ".git",
"Embed": `<iframe src="https://` + s.rawHost() + `/embed/` + gist.ID + `" style="width:100%;height:24em;border:0" loading="lazy"></iframe>`,
}
if c, err := s.gistGit(gist).Commit(commit); err == nil {
data["Last"] = c
}
if gist.Parent != "" {
if p, err := s.store.Gist(gist.Parent); err == nil && !p.Secret {
data["Parent"] = p
}
}
if forks, _ := s.store.GistForks(gist.ID); len(forks) > 0 {
data["Forks"] = forks
}
s.render(w, r, "gist", page{Title: gist.Title(files), User: user, Error: r.URL.Query().Get("error"), Math: math, Data: data})
}
func (s *Server) gistRevisions(w http.ResponseWriter, r *http.Request, gist Gist, user *User) {
g := s.gistGit(gist)
commits, _ := g.Log(s.gistHead(gist), 30, "")
type revision struct {
Commit Commit
Files []File
}
revs := make([]revision, 0, len(commits))
for _, c := range commits {
files, _ := g.Diff(c.Hash)
revs = append(revs, revision{Commit: c, Files: files})
}
s.render(w, r, "gistlog", page{Title: "Revisions of gist " + gist.ID[:8], User: user, Data: map[string]any{"Gist": gist, "Revisions": revs}})
}
func (s *Server) editGist(w http.ResponseWriter, r *http.Request, gist Gist, user *User) {
if user == nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
if user.ID != gist.Owner.ID {
s.fail(w, r, 403, "Only the owner can edit this gist")
return
}
g := s.gistGit(gist)
head := s.gistHead(gist)
if r.Method == "POST" {
r.Body = http.MaxBytesReader(w, r.Body, 8<<20)
if err := r.ParseForm(); err != nil {
s.fail(w, r, 400, "The gist is too large")
return
}
head = r.FormValue("head")
}
entries, err := g.gistTree(head)
if err != nil {
s.fail(w, r, 409, "The gist changed while you were editing it, reload and try again")
return
}
var files []gistFile
var keep []gistEntry
for _, e := range entries {
if e.Size <= gistWebFile {
if content, err := g.run(nil, "cat-file", "blob", e.OID); err == nil && !isBinary(content) {
files = append(files, gistFile{Orig: e.Name, Name: e.Name, Content: string(content)})
continue
}
}
keep = append(keep, e)
}
data := map[string]any{"Gist": gist, "Files": files, "Keep": keep, "Head": head, "Action": "/gist/" + gist.ID + "/edit", "Description": gist.Description, "Secret": gist.Secret}
if r.Method != "POST" {
s.render(w, r, "gistform", page{Title: "Edit gist", User: user, Data: data})
return
}
posted := formFiles(r)
secret := r.FormValue("visibility") == "secret"
data["Files"], data["Description"], data["Secret"] = posted, r.FormValue("description"), secret
if r.FormValue("action") == "add" {
data["Files"] = append(posted, gistFile{})
s.render(w, r, "gistform", page{Title: "Edit gist", User: user, Data: data})
return
}
retry := func(msg string) {
w.WriteHeader(400)
s.render(w, r, "gistform", page{Title: "Edit gist", User: user, Error: msg, Data: data})
}
description, err := cleanDescription(r.FormValue("description"))
if err != nil {
retry(err.Error())
return
}
if over, used, quota := overQuota(s.root, user.Name); over {
retry(quotaMessage(used, quota))
return
}
if _, err := s.writeGist(g, head, posted, keep, *user, "Edit gist"); err != nil && !errors.Is(err, errNoChange) {
retry(err.Error())
return
}
s.store.UpdateGist(gist.ID, description, secret)
http.Redirect(w, r, "/gist/"+gist.ID, http.StatusSeeOther)
}
func (s *Server) gistSmart(w http.ResponseWriter, r *http.Request, gist Gist, rest string) {
service := r.URL.Query().Get("service")
if rest != "info/refs" {
service = rest
}
if service != "git-upload-pack" && service != "git-receive-pack" {
http.Error(w, "unsupported service", 403)
return
}
var recv, env []string
limit := int64(0)
if service == "git-receive-pack" {
ip := clientIP(r)
if s.limiter.blocked(ip) {
http.Error(w, "too many failed attempts", 429)
return
}
u, ok := s.basicUser(r)
if !ok || u.ID != gist.Owner.ID {
if _, _, given := r.BasicAuth(); given {
s.limiter.fail(ip)
}
w.Header().Set("WWW-Authenticate", `Basic realm="`+s.host+`"`)
http.Error(w, "authentication required", 401)
return
}
if !hooksReady(s.root) {
http.Error(w, "pushes are unavailable right now", 503)
return
}
over, used, quota := overQuota(s.root, gist.Owner.Name)
if over {
http.Error(w, quotaMessage(used, quota), 403)
return
}
if quota > 0 {
limit = quota - used + 1<<20
}
recv, env = gistReceiveArgs(s.root, gist.Owner.Name), gistEnv(gist, u)
}
s.gitService(w, r, s.gistGit(gist).Dir, service, rest, recv, env, limit)
if service == "git-receive-pack" && rest != "info/refs" {
s.store.TouchGist(gist.ID)
}
}
const rawPolicy = "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox"
const embedPolicy = "default-src 'none'; style-src 'unsafe-inline'; img-src https: data:; base-uri 'none'; form-action 'none'; frame-ancestors *"
func (s *Server) serveGistRaw(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "no-referrer")
if r.Method != "GET" && r.Method != "HEAD" {
h.Set("Allow", "GET, HEAD")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if !s.requests.allow(clientIP(r)) {
h.Set("Retry-After", "10")
http.Error(w, "too many requests, slow down", http.StatusTooManyRequests)
return
}
notFound := func() { http.Error(w, "not found", http.StatusNotFound) }
kind, rest, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/")
id, rest, _ := strings.Cut(rest, "/")
if kind == "" {
http.Redirect(w, r, "https://"+s.host+"/gists", http.StatusFound)
return
}
if !gistID.MatchString(id) {
notFound()
return
}
gist, err := s.store.Gist(id)
if err != nil {
notFound()
return
}
g := s.gistGit(gist)
switch kind {
case "embed":
if rest != "" {
notFound()
return
}
s.gistEmbed(w, r, gist)
case "raw":
commit, file := s.gistHead(gist), rest
pinned := false
if rev, name, ok := strings.Cut(rest, "/"); ok && fullOID.MatchString(rev) {
c, err := g.Resolve(rev + "^{commit}")
if err != nil {
notFound()
return
}
commit, file, pinned = c, name, true
}
if commit == "" || checkGistName(file) != nil {
notFound()
return
}
mode, oid, ok := g.pageEntry(commit, file)
if !ok || (mode != "100644" && mode != "100755") {
notFound()
return
}
data, err := g.run(nil, "cat-file", "blob", oid)
if err != nil || len(data) > gistPushFile {
notFound()
return
}
ctype := "text/plain; charset=utf-8"
if kind := mediaTypes[strings.ToLower(filepath.Ext(file))]; strings.HasPrefix(kind, "image/") {
ctype = kind
}
h.Set("Content-Type", ctype)
h.Set("Content-Security-Policy", rawPolicy)
h.Set("Access-Control-Allow-Origin", "*")
h.Set("Cross-Origin-Resource-Policy", "cross-origin")
h.Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": file}))
if pinned {
h.Set("Cache-Control", "public, max-age=31536000, immutable")
} else {
h.Set("Cache-Control", "public, max-age=60")
}
h.Set("Content-Length", strconv.Itoa(len(data)))
w.Write(data)
default:
notFound()
}
}
var embedTemplate = template.Must(template.New("embed").Funcs(template.FuncMap{
"lines": func(b []byte) []string { return strings.Split(strings.TrimSuffix(string(b), "\n"), "\n") },
"inc": func(i int) int { return i + 1 },
}).Parse(`<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{{.Title}}</title>
<style>
body{margin:0;font:14px/1.5 system-ui,sans-serif;color:#1f2328;background:#fff}
.file{border:1px solid #d0d7de;border-radius:6px;margin:0 0 12px;overflow:hidden}
.head{display:flex;justify-content:space-between;gap:8px;padding:6px 10px;background:#f6f8fa;border-bottom:1px solid #d0d7de;font-size:12px}
.head a{color:#0969da;text-decoration:none}
.body{overflow:auto;max-height:40em}
pre,code,table.blob{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;margin:0}
.chroma{padding:8px 0}
.chroma .lntd:first-child{padding:0 8px;color:#8c959f;user-select:none}
.chroma .lnlinks{color:#8c959f;text-decoration:none}
table.blob td.n{padding:0 8px;color:#8c959f;text-align:right;user-select:none}
table.blob td.l{white-space:pre;padding-right:8px}
.readme{padding:8px 16px}
img{max-width:100%}
.note{padding:8px 10px;color:#59636e}
{{.CSS}}
</style></head><body>
{{range .Files}}<div class="file"><div class="head"><span>{{.Name}}</span><span><a href="{{.Raw}}" target="_blank" rel="noopener">raw</a> ยท <a href="{{$.Link}}" target="_blank" rel="noopener">hosted on {{$.Host}}</a></span></div><div class="body">
{{if .Image}}<img src="{{.Raw}}" alt="{{.Name}}">{{else if .Binary}}<p class="note">Binary file.</p>{{else if .Large}}<p class="note">File too large to display.</p>{{else if .Markdown}}<div class="readme">{{.Markdown}}</div>{{else if .Highlighted}}{{.Highlighted}}{{else}}<table class="blob">{{range $i, $l := lines .Content}}<tr><td class="n">{{inc $i}}</td><td class="l">{{$l}}</td></tr>{{end}}</table>{{end}}
</div></div>{{end}}
</body></html>
`))
func (s *Server) gistEmbed(w http.ResponseWriter, r *http.Request, gist Gist) {
head := s.gistHead(gist)
if head == "" {
http.Error(w, "not found", http.StatusNotFound)
return
}
views := s.gistViews(gist, head, 0)
var names []string
for _, v := range views {
names = append(names, v.Name)
}
h := w.Header()
h.Set("Content-Type", "text/html; charset=utf-8")
h.Set("Content-Security-Policy", embedPolicy)
h.Set("Cache-Control", "public, max-age=60")
embedTemplate.Execute(w, map[string]any{
"Title": gist.Title(names), "Files": views, "Host": s.host, "Link": "https://" + s.host + "/gist/" + gist.ID,
"CSS": template.CSS(highlightCSS()),
})
}
type apiGistFile struct {
Filename string `json:"filename"`
Size int64 `json:"size"`
RawURL string `json:"raw_url"`
Content string `json:"content,omitempty"`
Truncated bool `json:"truncated"`
}
type apiGist struct {
ID string `json:"id"`
Description string `json:"description"`
Public bool `json:"public"`
Owner string `json:"owner"`
HTMLURL string `json:"html_url"`
GitPullURL string `json:"git_pull_url"`
EmbedURL string `json:"embed_url"`
Created string `json:"created_at"`
Updated string `json:"updated_at"`
Files map[string]apiGistFile `json:"files"`
}
func (s *Server) apiView(gist Gist) apiGist {
out := apiGist{ID: gist.ID, Description: gist.Description, Public: !gist.Secret, Owner: gist.Owner.Name,
HTMLURL: "https://" + s.host + "/gist/" + gist.ID, GitPullURL: "https://" + s.host + "/gist/" + gist.ID + ".git",
EmbedURL: "https://" + s.rawHost() + "/embed/" + gist.ID,
Created: gist.Created.UTC().Format(time.RFC3339), Updated: gist.Updated.UTC().Format(time.RFC3339), Files: map[string]apiGistFile{}}
g := s.gistGit(gist)
head := s.gistHead(gist)
entries, _ := g.gistTree(head)
for _, e := range entries {
f := apiGistFile{Filename: e.Name, Size: e.Size, RawURL: s.rawURL(gist, head, e.Name)}
if e.Size > gistWebFile {
f.Truncated = true
} else if data, err := g.run(nil, "cat-file", "blob", e.OID); err == nil && !isBinary(data) {
f.Content = string(data)
}
out.Files[e.Name] = f
}
return out
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
enc.Encode(v)
}
func (s *Server) apiGist(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
gist, err := s.store.Gist(id)
if !gistID.MatchString(id) || err != nil {
writeJSON(w, 404, map[string]string{"message": "gist not found"})
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
writeJSON(w, 200, s.apiView(gist))
}
func (s *Server) apiCreateGist(w http.ResponseWriter, r *http.Request) {
ip := clientIP(r)
if s.limiter.blocked(ip) {
writeJSON(w, 429, map[string]string{"message": "too many failed attempts"})
return
}
u, ok := s.basicUser(r)
if !ok {
if _, _, given := r.BasicAuth(); given {
s.limiter.fail(ip)
}
w.Header().Set("WWW-Authenticate", `Basic realm="`+s.host+`"`)
writeJSON(w, 401, map[string]string{"message": "authenticate with your name and an access token"})
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20))
if err != nil {
writeJSON(w, 413, map[string]string{"message": "request too large"})
return
}
isJSON := strings.HasPrefix(r.Header.Get("Content-Type"), "application/json")
var description string
var public bool
var files []gistFile
if isJSON {
var req struct {
Description string `json:"description"`
Public bool `json:"public"`
Files map[string]struct {
Content string `json:"content"`
} `json:"files"`
}
if err := json.Unmarshal(body, &req); err != nil {
writeJSON(w, 400, map[string]string{"message": "invalid JSON: " + err.Error()})
return
}
description, public = req.Description, req.Public
for name, f := range req.Files {
files = append(files, gistFile{Name: name, Content: f.Content})
}
sort.Slice(files, func(i, j int) bool { return files[i].Name < files[j].Name })
} else {
q := r.URL.Query()
description = q.Get("description")
public = q.Get("public") == "1" || q.Get("public") == "true"
files = []gistFile{{Name: q.Get("file"), Content: string(body)}}
}
gist, err := s.createGist(u, description, !public, files)
if err != nil {
writeJSON(w, 422, map[string]string{"message": err.Error()})
return
}
if !isJSON {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(201)
fmt.Fprintln(w, "https://"+s.host+"/gist/"+gist.ID)
return
}
writeJSON(w, 201, s.apiView(gist))
}
|