populate font list, add more badge styles

main
Nick Dumas 1 year ago
parent 57103c3fc2
commit 781a718e42

@ -1,8 +1,13 @@
package main package main
import ( import (
"encoding/json"
"flag" "flag"
"fmt" "fmt"
"io/fs"
"os"
"path/filepath"
"strings"
// "log" // "log"
"net/http" "net/http"
"strconv" "strconv"
@ -18,15 +23,38 @@ type BadgeRenderer struct {
Fonts map[string]string Fonts map[string]string
} }
func NewBadgeRenderer() *BadgeRenderer { func NewBadgeRenderer(fontDir string) (*BadgeRenderer, error) {
var br BadgeRenderer var br BadgeRenderer
br.Fonts = make(map[string]string) br.Fonts = make(map[string]string)
// walkfunc to find ttf files here root := os.DirFS(fontDir)
return &br err := fs.WalkDir(root, ".", func(path string, d fs.DirEntry, err error) error {
if strings.HasSuffix(path, ".ttf") {
br.Fonts[filepath.Base(path)] = path
}
return nil
})
if err != nil {
return &br, fmt.Errorf("error walking for font files: %w", err)
}
return &br, nil
} }
func (br *BadgeRenderer) listFonts(w http.ResponseWriter, r *http.Request) { func (br *BadgeRenderer) listFonts(w http.ResponseWriter, r *http.Request) {
style := chi.URLParam(r, "format")
switch style {
case "json":
w.Header().Add("Content-Type", "application/json")
enc := json.NewEncoder(w)
err := enc.Encode(br.Fonts)
if err != nil {
w.WriteHeader(400)
fmt.Fprintf(w, "couldn't encode font list to json: %s\n", err)
}
}
} }
func (br *BadgeRenderer) renderBadge(w http.ResponseWriter, r *http.Request) { func (br *BadgeRenderer) renderBadge(w http.ResponseWriter, r *http.Request) {
@ -88,6 +116,16 @@ func (br *BadgeRenderer) renderBadge(w http.ResponseWriter, r *http.Request) {
switch q["style"][0] { switch q["style"][0] {
case "flat": case "flat":
fmt.Fprintf(w, "%s", bg.GenerateFlat(label, message, color)) fmt.Fprintf(w, "%s", bg.GenerateFlat(label, message, color))
case "flatsimple":
fmt.Fprintf(w, "%s", bg.GenerateFlatSimple(message, color))
case "flatsquare":
fmt.Fprintf(w, "%s", bg.GenerateFlatSquare(label, message, color))
case "flatsquaresimple":
fmt.Fprintf(w, "%s", bg.GenerateFlatSquareSimple(message, color))
case "plastic":
fmt.Fprintf(w, "%s", bg.GeneratePlastic(label, message, color))
case "plasticsimple":
fmt.Fprintf(w, "%s", bg.GeneratePlasticSimple(message, color))
default: default:
w.WriteHeader(400) w.WriteHeader(400)
@ -106,7 +144,11 @@ func main() {
flag.Parse() flag.Parse()
br := NewBadgeRenderer() br, err := NewBadgeRenderer(fontsDir)
if err != nil {
fmt.Println("couldn't create renderer", err)
return
}
r := chi.NewRouter() r := chi.NewRouter()
r.Use(middleware.Logger) r.Use(middleware.Logger)

Loading…
Cancel
Save