-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
132 lines (100 loc) · 2.49 KB
/
http.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
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
package main
import (
"context"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"golang.org/x/oauth2"
"github.com/google/go-github/github"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
)
type AppConfig struct {
client *github.Client
ctx context.Context
}
var cfg AppConfig
type RepoHealth struct {
RepoStats *RepoStats `json:"repo,omitempty"`
CommitStats *ParticipationStats `json:"participation,omitempty"`
}
func getRepoHealth(owner string, repo string) *RepoHealth {
repoStats := GetRepoStats(owner, repo)
partStats := GetParticipationStats(owner, repo)
rh := &RepoHealth{
RepoStats: repoStats,
CommitStats: partStats,
}
return rh
}
func ossNameHandler(w http.ResponseWriter, r *http.Request) {
data := mux.Vars(r)
log.Println(data)
rh := getRepoHealth(data["owner"], data["repo"])
jsonResponse, err := json.Marshal(rh)
if err != nil {
log.Panic(err)
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(jsonResponse)
}
func ossBadgeHandler(w http.ResponseWriter, r *http.Request) {
data := mux.Vars(r)
log.Println(data)
rh := getRepoHealth(data["owner"], data["repo"])
log.Println("RH:", &rh)
// TODO: Get actual score for Repo
grade := "A"
badgeUrl := getBadge(grade)
// Get badge image
// TODO:
// - This is a very stupid hack
// - We should be generating the badge ourselves, not proxying the badge
// from shields.io
resp, err := http.Get(badgeUrl)
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
w.Header().Add("Content-Type", "image/svg+xml;charset=utf-8")
w.WriteHeader(200)
w.Write(body)
}
func handlers() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/{owner}/{repo}", ossNameHandler).Methods("GET")
r.HandleFunc("/{owner}/{repo}/badge.svg", ossBadgeHandler).Methods("GET")
return r
}
func startServer() {
configureClient()
log.Println("serving...")
if os.Getenv("PORT") != "" {
http.ListenAndServe(strings.Join([]string{":", os.Getenv("PORT")}, ""), handlers())
} else {
http.ListenAndServe(":8080", handlers())
}
}
func main() {
startServer()
}
func configureClient() {
log.Println("Starting OSS Health App")
err := godotenv.Load()
if err != nil {
// No .env, so get settings from ENV
}
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: os.Getenv("OAUTH_TOKEN")},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
cfg.client = client
cfg.ctx = ctx
}