/
helpers.go
100 lines (84 loc) · 2.3 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
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
92
93
94
95
96
97
98
99
100
package handler
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gkarlik/expense-tracker/shared/errors"
"github.com/gkarlik/quark-go"
auth "github.com/gkarlik/quark-go/middleware/auth/jwt"
opentracing "github.com/opentracing/opentracing-go"
uuid "github.com/satori/go.uuid"
"golang.org/x/net/context"
"google.golang.org/grpc/metadata"
)
const (
CategoriesPageSize = 50
ExpensesPageSize = 50
UserClaimsKey = "USER_KEY"
UserIDKey = "UserID"
RequestIDKey = "Request-ID"
ErrorKey = "Error"
ErrorMetricName = "errors"
)
func GetContextWithSpan(s quark.Service, r *http.Request) context.Context {
ctx := context.Background()
if span := s.Tracer().SpanFromContext(r.Context()); span != nil {
md := metadata.Pairs()
if err := s.Tracer().InjectSpan(span, opentracing.TextMap, quark.RPCMetadataCarrier{MD: &md}); err != nil {
ctx = metadata.NewOutgoingContext(context.Background(), md)
}
}
return ctx
}
func GetUserID(r *http.Request) string {
if r == nil {
return ""
}
claims := r.Context().Value(UserClaimsKey).(auth.Claims)
userID := claims.Properties[UserIDKey].(string)
return userID
}
func GetRequestID(r *http.Request) string {
if r == nil {
return uuid.NewV4().String()
}
fmt.Println(r.Context())
reqID, ok := r.Context().Value(RequestIDKey).(string)
if !ok {
return ""
}
return reqID
}
func ParseRequestData(r *http.Request, in interface{}) ([]byte, error) {
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return b, err
}
err = json.Unmarshal(b, in)
if err != nil {
return b, err
}
return b, nil
}
func setResponse(w http.ResponseWriter, data []byte, code int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(data)
}
func Response(s quark.Service, w http.ResponseWriter, r *http.Request, in interface{}, code int) {
data, err := json.Marshal(in)
if err != nil {
ErrorResponse(s, w, r, errors.ErrInternal, http.StatusInternalServerError)
return
}
setResponse(w, data, code)
}
func ErrorResponse(s quark.Service, w http.ResponseWriter, r *http.Request, e *errors.Error, code int) {
data, err := json.Marshal(e)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
setResponse(w, data, code)
}