-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
81 lines (69 loc) · 2.04 KB
/
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
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
package handler
import (
"database/sql"
"encoding/json"
"log"
"net/http"
"github.com/dgrijalva/jwt-go"
"github.com/zachlatta/shelterconnect/database"
"github.com/zachlatta/shelterconnect/model"
)
// AppError represents an error as returned by this application. It works in
// tandem with AppHandler for easy handling of errors.
type AppError struct {
Error error `json:"-"`
Message string `json:"message"`
Code int `json:"code"`
}
// AppHandler is a type that implements http.Handler and makes handling
// errors easier. When its method returns an error, it prints it to the logs
// and shows a JSON formatted error to the user.
type AppHandler func(http.ResponseWriter, *http.Request,
*model.Organization) *AppError
func (fn AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var e *AppError
if r.Header.Get("Authorization") != "" {
var org *model.Organization
org, e = getUserFromToken(r)
if e == nil {
e = fn(w, r, org)
}
} else {
e = fn(w, r, nil)
}
if e != nil { // e is *AppError, not os.Error
log.Println(e.Error)
renderJSON(w, e, e.Code)
}
}
func getUserFromToken(r *http.Request) (*model.Organization, *AppError) {
token, err := jwt.ParseFromRequest(r, func(t *jwt.Token) ([]byte, error) {
// TODO: Use real secret
return []byte("secret"), nil
})
if err != nil {
return nil, &AppError{err, "bad authorization token",
http.StatusBadRequest}
}
id := int64(token.Claims["id"].(float64))
org, err := database.GetOrganizationByID(id)
if err != nil {
if err == sql.ErrNoRows {
return nil, &AppError{err, "user from token not found",
http.StatusNotFound}
}
return nil, &AppError{err, "error fetching user from database",
http.StatusInternalServerError}
}
return org, nil
}
func renderJSON(w http.ResponseWriter, data interface{}, code int) *AppError {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(code)
err := json.NewEncoder(w).Encode(data)
if err != nil {
return &AppError{err, "error encoding json",
http.StatusInternalServerError}
}
return nil
}