about summary refs log tree commit diff
path: root/main.go
blob: 859694dc4d72f33d563a50b99f6b9bb04a82c67a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"strings"
)

func main() {

	port := flag.String("port", "8080", "Port to serve static content")
	directory := flag.String("dir", ".", "directory that contain the static content")
	subpath := flag.String("subpath", "", "Domain subpath")
	flag.Parse()

	if len(*subpath) > 0 {
		http.Handle(fmt.Sprintf("/%s/", *subpath), preventDirListing(http.StripPrefix(fmt.Sprintf("/%s/", *subpath), http.FileServer(http.Dir(*directory)))))
		log.Printf("Using subpath: %s", *subpath)
	} else {
		http.Handle("/", preventDirListing(http.FileServer(http.Dir(*directory))))
	}

	log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
	log.Fatal(http.ListenAndServe(":"+*port, nil))

}

// Some hacky way to skip dir listing on / endpoints
func preventDirListing(h http.Handler) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if strings.HasSuffix(r.URL.Path, "/") {
			http.NotFound(w, r)
			return
		}
		h.ServeHTTP(w, r)
	})
}