2015-05-25 12:11:55 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/alecthomas/template"
|
|
|
|
"github.com/gorilla/mux"
|
2015-05-25 13:11:20 +00:00
|
|
|
"github.com/tdewolff/minify"
|
|
|
|
"github.com/tdewolff/minify/svg"
|
2015-05-25 12:11:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
xSpacing = 8
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
port := fmt.Sprintf(":%s", os.Getenv("PORT"))
|
|
|
|
if port == ":" {
|
|
|
|
port = ":3000"
|
|
|
|
}
|
|
|
|
|
|
|
|
r := mux.NewRouter()
|
|
|
|
r.HandleFunc("/v1/badge", generateBadge).Methods("GET")
|
|
|
|
|
|
|
|
http.Handle("/", r)
|
|
|
|
http.ListenAndServe(port, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
func generateBadge(res http.ResponseWriter, r *http.Request) {
|
|
|
|
title := r.URL.Query().Get("title")
|
|
|
|
text := r.URL.Query().Get("text")
|
2015-05-25 12:28:50 +00:00
|
|
|
color := r.URL.Query().Get("color")
|
2015-05-25 12:11:55 +00:00
|
|
|
|
|
|
|
if title == "" || text == "" {
|
|
|
|
http.Error(res, "You must specify parameters 'title' and 'text'.", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-05-25 12:28:50 +00:00
|
|
|
if color == "" {
|
|
|
|
color = "4c1"
|
|
|
|
}
|
|
|
|
|
|
|
|
badge := createBadge(title, text, color)
|
2015-05-25 12:11:55 +00:00
|
|
|
|
|
|
|
res.Header().Add("Content-Type", "image/svg+xml")
|
|
|
|
res.Header().Add("Cache-Control", "public, max-age=31536000")
|
2015-05-25 13:11:20 +00:00
|
|
|
|
|
|
|
m := minify.New()
|
|
|
|
m.AddFunc("image/svg+xml", svg.Minify)
|
|
|
|
|
|
|
|
badge, _ = minify.Bytes(m, "image/svg+xml", badge)
|
|
|
|
|
2015-05-25 12:11:55 +00:00
|
|
|
res.Write(badge)
|
|
|
|
}
|
|
|
|
|
2015-05-25 12:28:50 +00:00
|
|
|
func createBadge(title, text, color string) []byte {
|
2015-05-25 12:11:55 +00:00
|
|
|
var buf bytes.Buffer
|
|
|
|
bufw := bufio.NewWriter(&buf)
|
|
|
|
|
|
|
|
titleW, _ := calculateTextWidth(title)
|
|
|
|
textW, _ := calculateTextWidth(text)
|
|
|
|
|
|
|
|
width := titleW + textW + 4*xSpacing
|
|
|
|
|
|
|
|
t, _ := Asset("assets/badgeTemplate.tpl")
|
|
|
|
tpl, _ := template.New("svg").Parse(string(t))
|
|
|
|
|
|
|
|
tpl.Execute(bufw, map[string]interface{}{
|
|
|
|
"Width": width,
|
|
|
|
"TitleWidth": titleW + 2*xSpacing,
|
|
|
|
"Title": title,
|
|
|
|
"Text": text,
|
|
|
|
"TitleAnchor": titleW/2 + xSpacing,
|
|
|
|
"TextAnchor": titleW + textW/2 + 3*xSpacing,
|
2015-05-25 12:28:50 +00:00
|
|
|
"Color": color,
|
2015-05-25 12:11:55 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
bufw.Flush()
|
|
|
|
return buf.Bytes()
|
|
|
|
}
|