Skip to content

Instantly share code, notes, and snippets.

@mutantcornholio
Created May 23, 2018 23:12
Show Gist options
  • Select an option

  • Save mutantcornholio/1af44806983fc9830ca3a902043f517d to your computer and use it in GitHub Desktop.

Select an option

Save mutantcornholio/1af44806983fc9830ca3a902043f517d to your computer and use it in GitHub Desktop.
/*
Simple static file server in go
Usage:
-p="8100" port to serve on
-d="." the directory of static files to host
-c enable cache
-4 ipv4 only
-6 ipv6 only
Navigating to http://localhost:8100 will display the index.html or directory
listing file.
*/
package main
import (
"flag"
"log"
"net"
"net/http"
)
type appHandler struct {
http.Handler
Cache bool
FileServer http.Handler
}
func (h *appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h.Cache {
w.Header().Set("Cache-Control", "public, max-age=7776000")
} else {
w.Header().Set("Cache-Control", "no-cache")
}
h.FileServer.ServeHTTP(w, r)
}
func main() {
port := flag.String("p", "8100", "port to serve on")
directory := flag.String("d", ".", "the directory of static file to host")
cache := flag.Bool("c", false, "use cache")
ipv4 := flag.Bool("4", false, "use ipv4 only")
ipv6 := flag.Bool("6", false, "use ipv6 only")
flag.Parse()
if *ipv4 && *ipv6 {
log.Fatal("Choose either -4 or -6")
}
h := &appHandler{
Cache: *cache,
FileServer: http.FileServer(http.Dir((*directory))),
}
server := &http.Server{
Handler: h,
}
family := "tcp"
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
if *ipv6 {
family = "tcp6"
} else if *ipv4 {
family = "tcp4"
}
l, err := net.Listen(family, ":"+*port)
if err != nil {
log.Fatal(err)
}
log.Fatal(server.Serve(l))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment