Skip to content

Instantly share code, notes, and snippets.

@artyom
Last active November 8, 2019 10:06
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 artyom/3e3edb72e22aafb353cb079f47e287f0 to your computer and use it in GitHub Desktop.
Save artyom/3e3edb72e22aafb353cb079f47e287f0 to your computer and use it in GitHub Desktop.
FROM golang:alpine AS builder
WORKDIR /app
ENV GOPROXY=https://proxy.golang.org CGO_ENABLED=0
COPY . .
RUN go build -ldflags='-s -w' -o server
FROM scratch
EXPOSE 8080
VOLUME /web
COPY --from=builder /app/server .
CMD ["./server", "-addr", ":8080", "-dir", "/web", "-ping"]
module github.com/artyom/web-server
go 1.13
// TODO describe program
package main
import (
"errors"
"flag"
"net/http"
"os"
"strings"
"time"
)
func main() {
p, dir, addr := "/", "/web", "localhost:8080"
var withPing bool
flag.StringVar(&p, "prefix", p, "path prefix to expose directory at")
flag.StringVar(&dir, "dir", dir, "path to directory to serve")
flag.StringVar(&addr, "addr", addr, "address to listen")
flag.BoolVar(&withPing, "ping", false, "internally handle /ping endpoint (useful for health checks)")
flag.Parse()
if err := run(p, dir, addr, withPing); err != nil {
os.Stderr.WriteString(err.Error() + "\n")
os.Exit(1)
}
}
func run(p, dir, addr string, withPing bool) error {
if !strings.HasPrefix(p, "/") {
return errors.New("prefix should be a /-separated path starting with /")
}
mux := http.NewServeMux()
if withPing && p != "/ping" {
mux.HandleFunc("/ping", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("pong\n")) })
}
if !strings.HasSuffix(p, "/") {
p += "/"
}
mux.Handle(p, http.StripPrefix(p, http.FileServer(http.Dir(dir))))
server := &http.Server{
Handler: mux,
Addr: addr,
ReadTimeout: time.Second,
WriteTimeout: time.Minute,
}
return server.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment