-
Notifications
You must be signed in to change notification settings - Fork 2
/
readme-score-api.go
249 lines (212 loc) · 6 KB
/
readme-score-api.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
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
package main
import (
"bytes"
"crypto/md5"
"encoding/json"
"errors"
"fmt"
"github.com/garyburd/redigo/redis"
"github.com/go-martini/martini"
"io"
"io/ioutil"
"log"
"net/http"
"os/exec"
"strconv"
"strings"
"text/template"
)
// Expire caches in an hour
const CACHE_TTL = 60 * 60
type Score struct {
TotalScore float32 `json:"total_score"`
Breakdown map[string]float32 `json:"breakdown"`
HumanBreakdown map[string][]float32 `json:"human_breakdown"`
}
type ScoreResponse struct {
Score float32 `json:"score"`
URL string `json:"url"`
Breakdown map[string]float32 `json:"breakdown"`
}
type HumanScoreResponse struct {
Score float32 `json:"score"`
URL string `json:"url"`
Breakdown map[string][]float32 `json:"breakdown"`
}
type ScoreSVG struct {
ThreeDigitLayout bool
SingleDigitLayout bool
Value string
Color string
}
type ErrorResponse struct {
Error string `json:"error"`
}
func MarshalToJsonBytes(res interface{}) []byte {
resAsJson, _ := json.Marshal(res)
return ([]byte(resAsJson))
}
func GetScoreResponseAsJson(score Score, url_or_slug string, human_breakdown bool) []byte {
var res interface{}
if human_breakdown {
res = &HumanScoreResponse{
Score: score.TotalScore,
Breakdown: score.HumanBreakdown,
URL: url_or_slug}
} else {
res = &ScoreResponse{
Score: score.TotalScore,
Breakdown: score.Breakdown,
URL: url_or_slug}
}
return MarshalToJsonBytes(res)
}
func (score Score) AsColor() string {
if score.TotalScore < 25 {
return "#E74C3C"
}
if score.TotalScore < 80 {
return "#F39C12"
}
return "#2ECC71"
}
func (score Score) AsScoreTemplate() ScoreSVG {
return ScoreSVG{
ThreeDigitLayout: score.TotalScore >= 100,
SingleDigitLayout: score.TotalScore < 10,
Value: strconv.Itoa(int(score.TotalScore)),
Color: score.AsColor(),
}
}
var score_template_string = ""
var score_template = template.New("score template")
func GetScoreResponseAsSVG(score_svg ScoreSVG) []byte {
var doc bytes.Buffer
var err error
if score_template_string == "" {
var score_template_bytes []byte
if score_template_bytes, err = ioutil.ReadFile("./templates/score.svg"); err == nil {
score_template_string = string(score_template_bytes)
}
score_template, err = score_template.Parse(score_template_string)
}
if err == nil {
err = score_template.Execute(&doc, score_svg)
}
HandleError(err)
return doc.Bytes()
}
func GetScoreErrorAsSVG() []byte {
return GetScoreResponseAsSVG(ScoreSVG{
Value: "Err",
Color: "#838383",
})
}
func GetScoreErrorAsJson(url_or_slug string) []byte {
res := &ErrorResponse{
Error: "Could not determine score for " + url_or_slug}
return MarshalToJsonBytes(res)
}
func CacheKeyForUrlOrSlug(url_or_slug string) string {
return "url_or_slug_v4:" + url_or_slug
}
func WriteSVGWithETag(res http.ResponseWriter, body []byte) {
hash := md5.New()
io.WriteString(hash, string(body))
etag := fmt.Sprintf("\"%x\"", hash.Sum(nil))
res.Header().Set("ETag", etag)
res.Write(body)
}
func (server *Server) GetScore(res http.ResponseWriter, req *http.Request, params martini.Params) {
query_params := req.URL.Query()
url_or_slug := ""
ok := false
human_breakdown := false
force := false
format := params["format"]
if format == "svg" {
res.Header().Set("Content-Type", "image/svg+xml")
res.Header().Set("Cache-Control", "no-cache, private")
} else if format == "txt" {
res.Header().Set("Content-Type", "text/plain")
} else {
res.Header().Set("Content-Type", "application/json")
}
var param_matches []string
var score *Score
var err error
if param_matches, ok = query_params["url"]; !ok {
param_matches = query_params["github"]
}
if len(param_matches) == 0 {
err = errors.New("No value for :url or :github query parameter")
}
if err == nil {
url_or_slug = strings.ToLower(param_matches[0])
if param_matches, ok = query_params["human_breakdown"]; ok {
human_breakdown = param_matches[0] == "true"
}
if param_matches, ok = query_params["force"]; ok {
force = true
}
score, err = server.GetScoreForUrlOrSlug(url_or_slug, force)
}
HandleError(err)
if score == nil {
if format == "svg" {
WriteSVGWithETag(res, GetScoreErrorAsSVG())
} else if format == "txt" {
res.Write([]byte("error"))
} else {
res.Write(GetScoreErrorAsJson(url_or_slug))
}
} else {
if format == "svg" {
WriteSVGWithETag(res, GetScoreResponseAsSVG(score.AsScoreTemplate()))
} else if format == "txt" {
res.Write([]byte(strconv.Itoa(int(score.TotalScore))))
} else {
res.Write(GetScoreResponseAsJson(*score, url_or_slug, human_breakdown))
}
}
}
func (server *Server) GetCachedScoreForUrlOrSlug(url_or_slug string) (*Score, error) {
var score *Score
scoreJson, err := redis.String(server.Redis("GET", CacheKeyForUrlOrSlug(url_or_slug)))
if scoreJson != "" {
score = &Score{}
if err = json.Unmarshal([]byte(scoreJson), &score); err != nil {
score = nil
}
}
return score, err
}
func (server *Server) CacheScoreForUrlOrSlug(scoreJson string, url_or_slug string) {
server.Redis("SET", CacheKeyForUrlOrSlug(url_or_slug), scoreJson)
server.Redis("EXPIRE", CacheKeyForUrlOrSlug(url_or_slug), CACHE_TTL)
}
func (server *Server) GetScoreForUrlOrSlug(url_or_slug string, force bool) (*Score, error) {
var score *Score
var err error
if score, err = server.GetCachedScoreForUrlOrSlug(url_or_slug); err != nil || force {
log.Printf("Cache miss for %s (forced? %t)", url_or_slug, force)
log.Print(err)
rubyCmd := exec.Command("./get_score.rb", url_or_slug)
var scoreOut []byte
if scoreOut, err = rubyCmd.Output(); err == nil {
lines := strings.Split(string(scoreOut), "\n")
scoreJson := lines[len(lines)-2]
server.CacheScoreForUrlOrSlug(scoreJson, url_or_slug)
score = &Score{}
if err = json.Unmarshal([]byte(scoreJson), &score); err != nil {
score = nil
}
}
}
return score, err
}
func main() {
server := &Server{}
fmt.Printf("%p\n", &(*server))
server.Start()
}