You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
badges/cmd/web/main.go

120 lines
2.3 KiB
Go

package main
import (
"flag"
"fmt"
// "log"
"net/http"
"strconv"
"code.ndumas.com/ndumas/badges"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
var FONT_PATH = "fonts"
type BadgeRenderer struct {
Fonts map[string]string
}
func NewBadgeRenderer() *BadgeRenderer {
var br BadgeRenderer
br.Fonts = make(map[string]string)
// walkfunc to find ttf files here
return &br
}
func (br *BadgeRenderer) listFonts(w http.ResponseWriter, r *http.Request) {
}
func (br *BadgeRenderer) renderBadge(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if len(q["label"]) < 1 {
w.WriteHeader(400)
fmt.Fprintf(w, "please provide a label")
}
label := q["label"][0]
if len(q["message"]) < 1 {
w.WriteHeader(400)
fmt.Fprintf(w, "please provide a message")
}
message := q["message"][0]
if len(q["color"]) < 1 {
w.WriteHeader(400)
fmt.Fprintf(w, "please provide a color")
}
color := q["color"][0]
if len(q["size"]) < 1 {
w.WriteHeader(400)
fmt.Fprintf(w, "please provide a size")
}
size, err := strconv.ParseInt(q["size"][0], 10, 64)
if err != nil {
w.WriteHeader(400)
fmt.Fprintf(w, "could not convert size to integer: %s\n", err)
return
}
if len(q["font"]) < 1 {
w.WriteHeader(400)
fmt.Fprintf(w, "please provide a font name")
}
font, ok := br.Fonts[q["font"][0]]
if !ok {
w.WriteHeader(400)
fmt.Fprintf(w, "unknown font selection\n")
}
bg, err := badge.NewGenerator(font, int(size))
if err != nil {
w.WriteHeader(400)
fmt.Fprintf(w, "error instantitating generator: %s\n", err)
return
}
w.Header().Add("Content-Type", "image/svg+xml")
switch q["style"][0] {
case "flat":
fmt.Fprintf(w, "%s", bg.GenerateFlat(label, message, color))
default:
w.WriteHeader(400)
fmt.Fprintf(w, "no matching style found\n")
}
}
var (
port int
fontsDir string
)
func main() {
flag.IntVar(&port, "port", 8484, "http listening port")
flag.StringVar(&fontsDir, "fonts", "fonts/", "directory containing ttf files")
flag.Parse()
br := NewBadgeRenderer()
r := chi.NewRouter()
r.Use(middleware.Logger)
// r.Use(middleware.Recoverer)
r.Use(middleware.Compress(5, "image/svg+xml"))
r.Get("/badge", br.renderBadge)
r.Get("/fonts/{format}", br.listFonts)
http.ListenAndServe(fmt.Sprintf(":%d", port), r)
}