Serve web files in go

This commit is contained in:
2023-08-31 20:27:43 -04:00
parent e1e6e3650a
commit 1c742809a1
6 changed files with 37 additions and 33 deletions

37
main.go
View File

@@ -2,10 +2,12 @@ package main
import (
"crypto/rand"
"embed"
"encoding/json"
"flag"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path"
@@ -18,16 +20,47 @@ import (
)
var (
imagesDir string
collageDir string
imagesDir string
collageDir string
localAssets bool
)
//go:embed web/*
var webFS embed.FS
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 for testing")
flag.Parse()
nameGen := NewNameGen()
imagesDirFs := os.DirFS(imagesDir)
imagesURLPath := "images"
collagesPath := "collages"
addFileServer := func(path, dir string) {
httpFileServer := http.FileServer(http.Dir(dir))
http.Handle("/"+path+"/", http.StripPrefix("/"+path, httpFileServer))
}
addFileServer(imagesURLPath, imagesDir)
addFileServer(collagesPath, collageDir)
if localAssets {
httpFileServer := http.FileServer(http.Dir("web"))
http.Handle("/", httpFileServer)
} else {
fs, err := fs.Sub(webFS, "web")
if err != nil {
panic(err)
}
httpFileServer := http.FileServer(http.FS(fs))
http.Handle("/", httpFileServer)
}
http.HandleFunc("/make-collage", func(w http.ResponseWriter, r *http.Request) {
collageReq := collage.Request{}