Add anyhttp support (#17)

Reviewed-on: #17
Fixes #11
This commit is contained in:
Balakrishnan Balasubramanian 2023-09-11 21:16:10 -04:00
parent 6854a3e1f1
commit 61a8d4ca5c
3 changed files with 26 additions and 6 deletions

2
go.mod
View File

@ -3,7 +3,7 @@ module go.balki.me/collage-maker
go 1.21
require (
github.com/oliamb/cutter v0.2.2
go.balki.me/anyhttp v0.3.0
go.oneofone.dev/resize v1.0.1
)

4
go.sum
View File

@ -1,6 +1,6 @@
github.com/oliamb/cutter v0.2.2 h1:Lfwkya0HHNU1YLnGv2hTkzHfasrSMkgv4Dn+5rmlk3k=
github.com/oliamb/cutter v0.2.2/go.mod h1:4BenG2/4GuRBDbVm/OPahDVqbrOemzpPiG5mi1iryBU=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.balki.me/anyhttp v0.3.0 h1:WtBQ0rnkg567sX/O4ij/+qBbdCIUt5VURSe718sITBY=
go.balki.me/anyhttp v0.3.0/go.mod h1:JhfekOIjgVODoVqUCficjpIgmB3wwlB7jhN0eN2EZ/s=
go.oneofone.dev/resize v1.0.1 h1:HjpVar/4pxMGrjO44ThaMX1Q5UOBw0KxzbxxRDZPQuA=
go.oneofone.dev/resize v1.0.1/go.mod h1:zGFmn7q4EUZVlnDmxqf+b0mWpxsTt0MH2yx6ng8tpq0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=

26
main.go
View File

@ -1,6 +1,7 @@
package main
import (
"context"
"crypto/rand"
"embed"
"encoding/json"
@ -16,6 +17,8 @@ import (
"log/slog"
"go.balki.me/anyhttp"
"go.balki.me/anyhttp/idle"
"go.balki.me/collage-maker/collage"
)
@ -25,6 +28,7 @@ var (
localAssets bool
collageNameGen *nameGen
imagesDirFs fs.FS
listenAddr string
// go:embed web/*
webFS embed.FS
@ -34,6 +38,7 @@ 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.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()
@ -87,10 +92,25 @@ func main() {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write([]byte(collageFile))
if _, err := w.Write([]byte(collageFile)); err != nil {
slog.Error("Failed to write collageFile", "error", err)
}
})
if err := http.ListenAndServe(":8767", nil); err != nil {
slog.Error("http ListenAndServe failed", "error", err)
addrType, server, done, err := anyhttp.Serve(listenAddr, idle.WrapHandler(nil))
if err != nil {
slog.Error("anyhttp Serve failed", "error", err)
}
if addrType == anyhttp.SystemdFD {
if err := idle.Wait(30 * time.Minute); err != nil {
slog.Error("Failed to wait for idler", "error", err)
}
ctx, _ := context.WithTimeout(context.Background(), 1*time.Minute) // Don't want any stuck connections
if err := server.Shutdown(ctx); err != nil {
slog.Error("http server Shutdown failed", "error", err)
}
} else {
<-done
}
}