servedir/main.go

40 lines
951 B
Go
Raw Normal View History

2013-10-21 13:45:14 -07:00
package main
import (
2013-10-21 19:21:59 -07:00
"flag"
"fmt"
2013-10-21 13:45:14 -07:00
"log"
"net/http"
"os"
2013-10-21 19:44:52 -07:00
"strings"
2013-10-21 13:45:14 -07:00
)
2013-10-21 19:21:59 -07:00
var port = flag.Int("port", 8000, "port from which to serve")
2013-10-21 19:44:52 -07:00
var hidden = flag.Bool("hidden", false, "allow serving hidden dirs")
2013-10-21 19:21:59 -07:00
2013-10-21 13:45:14 -07:00
func logger(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2015-08-30 01:42:03 -07:00
w.Header().Add("Access-Control-Allow-Origin", "*")
2013-10-21 13:45:14 -07:00
log.Printf("%s: %s\n", r.RemoteAddr, r.URL)
2013-10-21 19:44:52 -07:00
if !*hidden && strings.Contains(r.URL.Path, "/.") {
http.Error(w, "hidden files and directories are not allowed", http.StatusUnauthorized)
return
}
2013-10-21 13:45:14 -07:00
h.ServeHTTP(w, r)
})
}
func main() {
2013-10-21 19:21:59 -07:00
flag.Parse()
hostname, err := os.Hostname()
if err != nil {
log.Fatal("problem getting hostname:", err)
}
log.Printf("serving on: http://%s:%d/", hostname, *port)
2013-10-21 19:21:59 -07:00
addr := fmt.Sprintf(":%d", *port)
2013-10-21 13:45:14 -07:00
fh := http.FileServer(http.Dir("./"))
2013-10-21 19:21:59 -07:00
if err := http.ListenAndServe(addr, logger(fh)); err != nil {
log.Fatal(err)
}
2013-10-21 13:45:14 -07:00
}