-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsysjson.go
91 lines (72 loc) · 1.99 KB
/
sysjson.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"encoding/base64"
"encoding/json"
"flag"
"log"
"net/http"
"strings"
)
var (
listen = flag.String("listen", ":5374", "Address to listen on")
tls = flag.Bool("tls", false, "Use TLS (requires -cert and -key)")
cert = flag.String("cert", "", "TLS cert file")
key = flag.String("key", "", "TLS key file")
password = flag.String("password", "", "Enable basic authentication")
)
func main() {
flag.Parse()
log.Printf("[notice] sys.json listening on %s", *listen)
mux := http.NewServeMux()
if len(*password) > 0 {
mux.HandleFunc("/", BasicAuth(statsHandler))
} else {
mux.HandleFunc("/", statsHandler)
}
if *tls {
log.Printf("[notice] Using TLS")
log.Fatal(http.ListenAndServeTLS(*listen, *cert, *key, mux))
} else {
log.Fatal(http.ListenAndServe(*listen, mux))
}
}
func statsHandler(w http.ResponseWriter, r *http.Request) {
resp := map[string]interface{}{}
loadModules(resp, r.URL.Query().Get("modules"))
respJSON, err := json.Marshal(resp)
if err != nil {
log.Fatal("[error] Fatal! Could not construct JSON response: %s", err)
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Write(respJSON)
}
func BasicAuth(pass http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if len(r.Header.Get("Authorization")) <= 0 {
http.Error(w, "authentication is required", http.StatusUnauthorized)
return
}
auth := strings.SplitN(r.Header["Authorization"][0], " ", 2)
if auth[0] != "Basic" || len(auth) != 2 {
http.Error(w, "bad syntax", http.StatusBadRequest)
return
}
payload, _ := base64.StdEncoding.DecodeString(auth[1])
parsed := string(payload)
if strings.Contains(parsed, ":") {
pair := strings.SplitN(string(payload), ":", 2)
parsed = pair[1]
}
if !Validate(parsed) {
http.Error(w, "authentication failed", http.StatusUnauthorized)
return
}
pass(w, r)
}
}
func Validate(pass string) bool {
if pass == *password {
return true
}
return false
}