package main import ( "flag" "fmt" "github.com/gorilla/mux" "gitto.work/shortcut/enhancedfileserver" "log" "net/http" ) type config struct { Listen string Port int Username string Password string } var c config func init() { flag.StringVar(&c.Listen, "listen", "0.0.0.0", "IP address to listen.") flag.IntVar(&c.Port, "port", 8000, "Listen port for interface (ports below 1024 may require super user privileges)") flag.StringVar(&c.Username, "username", "", "Require this username tp access") flag.StringVar(&c.Password, "password", "", "Require this password to access interface") flag.Parse() } func main() { r := mux.NewRouter() r.Use(BasicAuth) r.Use(QueryLog) r.PathPrefix("/").Handler(http.StripPrefix("/", enhancedfileserver.FileServer(http.Dir("./")))) a := fmt.Sprintf("%s:%d", c.Listen, c.Port) log.Fatal(http.ListenAndServe(a, r)) } func BasicAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if c.Username != "" && c.Password != "" { user, pass, ok := r.BasicAuth() if !ok || user != c.Username || pass != c.Password { w.Header().Set("WWW-Authenticate", `Basic realm="mydomains"`) http.Error(w, "Unauthorized", http.StatusUnauthorized) } } next.ServeHTTP(w, r) }) } func QueryLog(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("%s - %s", r.RemoteAddr, r.URL) next.ServeHTTP(w, r) }) }