simpleserve/main.go

48 lines
1.0 KiB
Go
Executable File

/*
Serve is a very simple static file server in go
Usage:
-p="8100": port to serve on
-d=".": the directory of static files to host
Navigating to http://localhost:8100 will display the index.html or directory
listing file.
*/
package main
import (
"local/args"
"local/gziphttp"
"log"
"net/http"
"strings"
)
func main() {
fs := args.NewArgSet()
fs.Append(args.STRING, "p", "port to serve", "8100")
fs.Append(args.STRING, "d", "static path to serve", "./public")
if err := fs.Parse(); err != nil {
panic(err)
}
d := fs.Get("d").GetString()
p := strings.TrimPrefix(fs.Get("p").GetString(), ":")
http.Handle("/", http.HandlerFunc(handler(d)))
log.Printf("Serving %s on HTTP port: %s\n", d, p)
log.Fatal(http.ListenAndServe(":"+p, nil))
}
func handler(d string) func(http.ResponseWriter, *http.Request) {
h := http.FileServer(http.Dir(d))
return func(w http.ResponseWriter, r *http.Request) {
if gziphttp.Can(r) {
gz := gziphttp.New(w)
defer gz.Close()
w = gz
}
h.ServeHTTP(w, r)
}
}