1
0
Fork 0
mirror of https://github.com/Luzifer/badge-gen.git synced 2024-11-08 13:20:02 +00:00
badge-gen/main.go

77 lines
1.5 KiB
Go
Raw Normal View History

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"
)
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")
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()
}