/
github.go
50 lines (46 loc) · 1.24 KB
/
github.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
package api
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"strings"
)
type GitHubContentResponse struct {
Name string `json:"name"`
Path string `json:"path"`
Content string `json:"content"`
Encoding string `json:"encoding"`
}
func (api *API) fetchGitHubFile(path string) ([]byte, error) {
req, err := http.NewRequest("GET", path, nil)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
if githubToken := os.Getenv("GITHUB_TOKEN"); githubToken != "" {
req.Header.Add("authorization", "token "+githubToken)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("do request: %w", err)
}
defer resp.Body.Close()
githubResp := GitHubContentResponse{}
err = json.NewDecoder(resp.Body).Decode(&githubResp)
if err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
if githubResp.Content == "" {
return nil, errors.New("missing content")
}
if githubResp.Encoding != "base64" {
return nil, fmt.Errorf("unknown encoding %s", githubResp.Encoding)
}
decoded, err := base64.StdEncoding.DecodeString(strings.ReplaceAll(githubResp.Content, "\n", ""))
if err != nil {
return nil, fmt.Errorf("decode base64 content: %w", err)
}
return decoded, nil
}