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
40
41
42
43
44
45
46
47
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)
}
|