From f1bd309910e6540bbd6b40adee8def114f62ea85 Mon Sep 17 00:00:00 2001 From: maride Date: Fri, 15 Feb 2019 17:13:22 +0100 Subject: Init --- main.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 main.go (limited to 'main.go') diff --git a/main.go b/main.go new file mode 100644 index 0000000..92e2d9c --- /dev/null +++ b/main.go @@ -0,0 +1,48 @@ +package main + +import ( + "fmt" + "net/http" + "log" +) + +var( + metrics_num_passwords int +) + +func main() { + log.Println("Starting HTTP listener") + + http.HandleFunc("/", httpHandler) + http.HandleFunc("/metrics", metricsHandler) + listenErr := http.ListenAndServe(":80", nil) // set listen port + if listenErr != nil { + log.Fatalln(listenErr.Error()) + } +} + +// Handling incoming HTTP connections +func httpHandler(w http.ResponseWriter, r *http.Request) { + // Raise stats + metrics_num_passwords++ + + // Log user/pass combo + user, pass, ok := r.BasicAuth() + + if ok { + // This also includes empty user/pass combos (if they are correctly encoded) + // To avoid them, use `len(user) > 0 && len(pass) > 0` + log.Printf("%s: %s %s:%s@%s%s", r.RemoteAddr, r.Method, user, pass, r.Host, r.URL.Path) + } else { + log.Printf("%s: %s %s%s", r.RemoteAddr, r.Method, r.Host, r.URL.Path) + } + + // Decline that try + w.Header().Set("WWW-Authenticate", `Basic realm="Protected Area"`) + w.WriteHeader(http.StatusUnauthorized) +} + +// Handle HTTP /metrics requests +func metricsHandler(w http.ResponseWriter, req *http.Request) { + fmt.Fprintf(w, "num_passwords %d\n", metrics_num_passwords) +} -- cgit 1.4.1