You've already forked collage-maker
Minor refactor
* Move namegen to seperate file * Simplify Makefile
This commit is contained in:
36
main.go
36
main.go
@@ -3,7 +3,6 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
@@ -14,7 +13,6 @@ import (
|
||||
"os"
|
||||
"path"
|
||||
"regexp"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"log/slog"
|
||||
@@ -27,7 +25,7 @@ import (
|
||||
var (
|
||||
imagesDir string
|
||||
collageDir string
|
||||
localAssets bool
|
||||
devMode bool
|
||||
collageNameGen *nameGen
|
||||
imagesDirFs fs.FS
|
||||
listenAddr string
|
||||
@@ -39,7 +37,7 @@ var (
|
||||
func main() {
|
||||
flag.StringVar(&imagesDir, "images-dir", "images", "Sets the images dir")
|
||||
flag.StringVar(&collageDir, "collages-dir", "collages", "Sets the collages dir")
|
||||
flag.BoolVar(&localAssets, "local-assets", false, "Serve local assets during development")
|
||||
flag.BoolVar(&devMode, "dev", false, "Serve local assets during development")
|
||||
flag.StringVar(&listenAddr, "addr", "127.0.0.1:8767", "Web listen address, see https://pkg.go.dev/go.balki.me/anyhttp#readme-address-syntax")
|
||||
|
||||
flag.Parse()
|
||||
@@ -57,7 +55,7 @@ func main() {
|
||||
addFileServer(imagesURLPath, imagesDir)
|
||||
addFileServer(collagesPath, collageDir)
|
||||
|
||||
if localAssets {
|
||||
if devMode {
|
||||
httpFileServer := http.FileServer(http.Dir("web"))
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Add("Cache-Control", "no-cache")
|
||||
@@ -131,39 +129,13 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
type nameGen struct {
|
||||
prefix string
|
||||
counter atomic.Uint64
|
||||
}
|
||||
|
||||
func NewNameGen() *nameGen {
|
||||
currentTime := time.Now().Unix()
|
||||
randBytes := make([]byte, 8)
|
||||
_, err := rand.Read(randBytes)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
alpha := []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||
uniqRunID := ""
|
||||
for _, b := range randBytes {
|
||||
uniqRunID += string(alpha[int(b)%len(alpha)])
|
||||
}
|
||||
return &nameGen{
|
||||
prefix: fmt.Sprintf("%d-%s", currentTime, uniqRunID),
|
||||
counter: atomic.Uint64{},
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
defer out.Close()
|
||||
if err := collage.Make(req, imagesDirFs, out); err != nil {
|
||||
return "", fmt.Errorf("failed to make collage, err: %w", err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user