forked from corestoreio/parrot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
63 lines (51 loc) · 1.35 KB
/
helpers.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
package auth
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/Sirupsen/logrus"
)
// getAuthHeaderToken gets the token string from the HTTP Authorization header.
func getAuthHeaderToken(r *http.Request) (string, error) {
token := r.Header.Get("Authorization")
if token == "" {
return "", fmt.Errorf("no auth header")
}
token = sanitizeBearerToken(token)
return token, nil
}
// getJSONBodyToken gets the token string from the HTTP JSON body.
func getJSONBodyToken(r *http.Request) (string, error) {
var body map[string]interface{}
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
return "", err
}
token, ok := body["token"].(string)
if token == "" || !ok {
return "", fmt.Errorf("no auth header")
}
token = sanitizeBearerToken(token)
return token, nil
}
// sanitizeBearerToken extracts the token part from the token string.
func sanitizeBearerToken(token string) string {
if len(token) > 6 && strings.ToUpper(token[0:7]) == "BEARER " {
return token[7:]
}
return token
}
func RenderJSON(w http.ResponseWriter, status int, headers map[string]string, payload interface{}) {
h := w.Header()
h.Set("Content-Type", "application/json")
for k, v := range headers {
h.Set(k, v)
}
w.WriteHeader(status)
encoded, err := json.MarshalIndent(payload, "", " ")
if err != nil {
logrus.Error(err)
}
w.Write(encoded)
}