minor refactor

This commit is contained in:
2023-09-01 15:13:54 -04:00
parent faa413c9b1
commit 1662ff226b
5 changed files with 31 additions and 17 deletions

41
main.go
View File

@@ -20,13 +20,15 @@ import (
)
var (
imagesDir string
collageDir string
localAssets bool
)
imagesDir string
collageDir string
localAssets bool
collageNameGen *nameGen
imagesDirFs fs.FS
//go:embed web/*
var webFS embed.FS
// go:embed web/*
webFS embed.FS
)
func main() {
flag.StringVar(&imagesDir, "images-dir", "images", "Sets the images dir")
@@ -34,8 +36,9 @@ func main() {
flag.BoolVar(&localAssets, "local-assets", false, "Serve local assets for testing")
flag.Parse()
nameGen := NewNameGen()
imagesDirFs := os.DirFS(imagesDir)
collageNameGen = NewNameGen()
imagesDirFs = os.DirFS(imagesDir)
imagesURLPath := "images"
collagesPath := "collages"
@@ -67,19 +70,18 @@ func main() {
body, err := io.ReadAll(r.Body)
if err != nil {
slog.Error("failed to read request body", "error", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if err := json.Unmarshal(body, &collageReq); err != nil {
slog.Error("failed to unmarshal json request", "error", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
collageFile := fmt.Sprintf("collage-%s.jpg", nameGen.Next())
out, err := os.Create(path.Join(collageDir, collageFile))
collageFile, err := MakeCollage(&collageReq)
if err != nil {
slog.Error("failed to create collage output file", "error", err)
}
if err := collage.Make(collageReq, imagesDirFs, out); err != nil {
slog.Error("failed to make collage", "error", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write([]byte(collageFile))
@@ -116,4 +118,17 @@ func (n *nameGen) Next() string {
return fmt.Sprintf("%s-%d", n.prefix, n.counter.Add(1))
}
func MakeCollage(req *collage.Request) (string, error) {
collageFile := fmt.Sprintf("collage-%s.jpg", collageNameGen.Next())
out, err := os.Create(path.Join(collageDir, collageFile))
if err != nil {
return "", fmt.Errorf("failed to create collage output file, err: %w", err)
// slog.Error("failed to create collage output file", "error", err)
}
if err := collage.Make(req, imagesDirFs, out); err != nil {
return "", fmt.Errorf("failed to make collage, err: %w", err)
}
return collageFile, nil
}
// curl -D - --json @req.json http://localhost:8767/make-collage