diff --git a/cmd/web/main.go b/cmd/web/main.go index 8848771..e46f7f9 100644 --- a/cmd/web/main.go +++ b/cmd/web/main.go @@ -1,8 +1,13 @@ package main import ( + "encoding/json" "flag" "fmt" + "io/fs" + "os" + "path/filepath" + "strings" // "log" "net/http" "strconv" @@ -18,15 +23,38 @@ type BadgeRenderer struct { Fonts map[string]string } -func NewBadgeRenderer() *BadgeRenderer { +func NewBadgeRenderer(fontDir string) (*BadgeRenderer, error) { var br BadgeRenderer br.Fonts = make(map[string]string) - // walkfunc to find ttf files here - return &br + root := os.DirFS(fontDir) + 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) { + 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) { @@ -88,6 +116,16 @@ func (br *BadgeRenderer) renderBadge(w http.ResponseWriter, r *http.Request) { switch q["style"][0] { case "flat": 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: w.WriteHeader(400) @@ -106,7 +144,11 @@ func main() { flag.Parse() - br := NewBadgeRenderer() + br, err := NewBadgeRenderer(fontsDir) + if err != nil { + fmt.Println("couldn't create renderer", err) + return + } r := chi.NewRouter() r.Use(middleware.Logger)