Skip to content

Instantly share code, notes, and snippets.

@amane-katagiri
Last active June 26, 2022 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amane-katagiri/7b9e09f27d329515f423c97da35335b1 to your computer and use it in GitHub Desktop.
Save amane-katagiri/7b9e09f27d329515f423c97da35335b1 to your computer and use it in GitHub Desktop.
Single binary HTTP server written in Go embedded with all static files.
#!/bin/bash -ue
if [ "$#" -lt 3 ]; then
echo "$0 BINARY_PREFIX STATIC_ROOT_DIR OUTPUT_DIR" >&2
exit 1
fi
export GOVER=1.18
export SUGOI_SRC='https://gist.githubusercontent.com/amane-katagiri/7b9e09f27d329515f423c97da35335b1/raw/0d1867886128375e30383f7b9aa470ff337a68a5/sugoi.go'
export PREFIX="$1"
export STATIC_ROOT="$2"
export OUTPUT_ROOT="$3"
mkdir -p "$OUTPUT_ROOT"
build() {
GOOS="$1"
GOARCH="$2"
SUFFIX=""
if [ "$GOOS" = windows ]; then
SUFFIX=".exe"
fi
BINARY="${OUTPUT_ROOT}/${PREFIX}.${GOOS}.${GOARCH}${SUFFIX}"
TMP="$(mktemp)"
docker run --rm -v "${STATIC_ROOT}:/go/output:ro" "golang:${GOVER}" bash -c "curl -Ss ${SUGOI_SRC} > sugoi.go && GOOS=${GOOS} GOARCH=${GOARCH} go build -o sugoi sugoi.go && cat sugoi" > "${TMP}"
chmod +x "$TMP"
mv "$TMP" "$BINARY"
}
build darwin amd64
build darwin arm64
build linux 386
build linux amd64
build linux arm64
build windows 386
build windows amd64
build windows arm64
package main
import (
"embed"
"flag"
"io/fs"
"log"
"net/http"
)
//go:embed output/*
var static embed.FS
func main() {
var (
port = flag.String("port", "0.0.0.0:8080", "serve port")
)
flag.Parse()
public, err := fs.Sub(static, "output")
if err != nil {
panic(err)
}
http.Handle("/", http.FileServer(http.FS(public)))
log.Printf("Serving site at: %s - Tap CTRL-C to stop", *port)
log.Fatal(http.ListenAndServe(*port, nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment