From 9a612a6281f9ce149ceb0761053db58c572c8815 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 2 Sep 2018 21:45:30 +0000 Subject: [PATCH] Initial import --- .gitignore | 1 + main.go | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 .gitignore create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c946e24 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +httphere diff --git a/main.go b/main.go new file mode 100644 index 0000000..9437d84 --- /dev/null +++ b/main.go @@ -0,0 +1,60 @@ +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.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="mydomain"`) + + 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) + }) +}