-
Notifications
You must be signed in to change notification settings - Fork 25
/
index.go
86 lines (73 loc) · 2.03 KB
/
index.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
package api
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/google/go-github/v40/github"
"golang.org/x/oauth2"
)
const USERNAME = "percival-bot"
const TOKEN_VAR = "GITHUB_TOKEN"
func tokenSource() oauth2.TokenSource {
token := os.Getenv(TOKEN_VAR)
if token == "" {
log.Fatalf("Could not find environment variable %v for authentication", TOKEN_VAR)
}
return oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
}
func Handler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
id := r.URL.Query().Get("id")
if id == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Missing `id` query field")
return
}
url := fmt.Sprintf("https://gist.githubusercontent.com/%v/%v/raw", USERNAME, id)
resp, err := http.Get(url)
if err != nil || resp.StatusCode != http.StatusOK {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Failed to fetch gist with ID %v", id)
return
}
result, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Failed to read body of gist GET response")
}
fmt.Fprint(w, string(result))
} else if r.Method == "POST" {
body, err := io.ReadAll(r.Body)
if err != nil || len(body) == 0 {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Missing body of POST request")
return
}
ctx := context.Background()
tc := oauth2.NewClient(ctx, tokenSource())
client := github.NewClient(tc)
public := false
description := "Code shared from a Percival notebook - https://percival.ink"
content := string(body)
gist, _, err := client.Gists.Create(ctx, &github.Gist{
Public: &public,
Description: &description,
Files: map[github.GistFilename]github.GistFile{
"notebook.percival": {Content: &content},
},
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "Failed to connect to GitHub API")
return
}
output, err := json.Marshal(gist)
if err != nil {
log.Fatalf("Failed to marshal result to json: %v", err)
}
fmt.Fprint(w, string(output))
}
}