-
Notifications
You must be signed in to change notification settings - Fork 7
/
util.go
50 lines (44 loc) · 900 Bytes
/
util.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
package util
import (
"encoding/json"
"net"
"net/http"
"net/url"
"time"
)
func SecondsSince(start time.Time) float64 {
return float64(time.Now().Sub(start).Seconds())
}
func JsonError(w http.ResponseWriter, msg string, code int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(
map[string]interface{}{
"value": map[string]string{
"message": msg,
},
"status": 13,
})
}
const UnknownUser = "unknown"
func RequestInfo(r *http.Request) (string, string) {
user := ""
if u, _, ok := r.BasicAuth(); ok {
user = u
} else {
user = UnknownUser
}
remote := r.Header.Get("X-Forwarded-For")
if remote != "" {
return user, remote
}
remote, _, _ = net.SplitHostPort(r.RemoteAddr)
return user, remote
}
func HostPort(input string) string {
u, err := url.Parse(input)
if err != nil {
panic(err)
}
return u.Host
}