This repository has been archived by the owner on Sep 8, 2021. It is now read-only.
/
api_cmd.go
90 lines (74 loc) · 2.05 KB
/
api_cmd.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
87
88
89
90
package cmd
import (
"context"
"fmt"
"net/http"
"strings"
"golang.org/x/oauth2"
"github.com/Sirupsen/logrus"
"github.com/google/go-github/github"
"github.com/netlify/gotell/api"
"github.com/netlify/gotell/conf"
"github.com/spf13/cobra"
)
func apiCommand() *cobra.Command {
return &cobra.Command{
Use: "api",
Short: "api",
Run: func(cmd *cobra.Command, args []string) {
execWithConfig(cmd, serveAPI)
},
}
}
func serveAPI(config *conf.Configuration) {
if err := verifyAPISettings(config); err != nil {
logrus.Fatalf("Error verifying settings: %v", err)
}
if err := verifySite(config.API.SiteURL); err != nil {
logrus.Fatalf("Error verifying site: %v", err)
}
githubClient := newGitHubClient(config)
if err := verifyRepoAndToken(config.API.Repository, githubClient); err != nil {
logrus.Fatalf("Error verifying repo: %v", err)
}
server := api.NewServerWithVersion(config, githubClient, Version)
server.ListenAndServe()
}
func verifyAPISettings(config *conf.Configuration) error {
if config.API.SiteURL == "" {
return fmt.Errorf("API requires a site url")
}
if config.API.Repository == "" {
return fmt.Errorf("API requires a GitHub repository path")
}
if config.API.AccessToken == "" {
return fmt.Errorf("API requires a GitHub access token")
}
return nil
}
func verifySite(url string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return fmt.Errorf("Expected 200 status code for %v, got %v", url, resp.StatusCode)
}
return nil
}
func verifyRepoAndToken(repository string, client *github.Client) error {
parts := strings.Split(repository, "/")
if len(parts) != 2 {
return fmt.Errorf("Repo format must be owner/repo - %v", repository)
}
ctx := context.Background()
_, _, err := client.Repositories.Get(ctx, parts[0], parts[1])
return err
}
func newGitHubClient(config *conf.Configuration) *github.Client {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: config.API.AccessToken},
)
tc := oauth2.NewClient(oauth2.NoContext, ts)
return github.NewClient(tc)
}