-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext.go
More file actions
161 lines (140 loc) · 4.28 KB
/
Copy pathcontext.go
File metadata and controls
161 lines (140 loc) · 4.28 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package flow
import (
"bytes"
"encoding/json"
"encoding/xml"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/pkg/errors"
"github.com/sedind/flow/auth/jwtauth"
"github.com/sedind/flow/dbe"
"github.com/sedind/flow/logger"
)
// Context -
type Context struct {
Config
DBConnections map[string]*dbe.Connection
Logger logger.Logger
jwtauth *jwtauth.JWTAuth
}
// JWTAuth gets JWTAuth object
func (c *Context) JWTAuth() *jwtauth.JWTAuth {
return c.jwtauth
}
// DefaultConnection gets default DB Connection
func (c *Context) DefaultConnection() (*dbe.Connection, error) {
if c, ok := c.DBConnections[c.Config.DefaultConnection]; ok {
return c, nil
}
return nil, errors.New("Default connection not defined in configuration")
}
// Transaction returns new Transaction on Detault Database connection
func (c *Context) Transaction() (*dbe.Connection, error) {
conn, err := c.DefaultConnection()
if err != nil {
return nil, err
}
return conn.NewTx()
}
// AppSetting gets appSetting string for given key
func (c *Context) AppSetting(key string) string {
if val, ok := c.AppSettings[key]; ok {
return val
}
return ""
}
// ResponseData creates response success object
func (c *Context) ResponseData(data interface{}) Response {
return Response{
Success: true,
Data: data,
}
}
// ResponseError creates response error object
func (c *Context) ResponseError(err error) Response {
return Response{
Success: false,
Error: err.Error(),
}
}
// JSON marshals 'v' to JSON, automatically escaping HTML and setting the
// Content-Type as application/json.
func (c *Context) JSON(w http.ResponseWriter, status int, v interface{}) {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(true)
if err := enc.Encode(v); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
w.Write(buf.Bytes())
}
// Plain writes a string to the response, setting the Content-Type as
// text/plain.
func (c *Context) Plain(w http.ResponseWriter, status int, v string) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(status)
w.Write([]byte(v))
}
// XML marshals 'v' to JSON, setting the Content-Type as application/xml. It
// will automatically prepend a generic XML header (see encoding/xml.Header) if
// one is not found in the first 100 bytes of 'v'.
func (c *Context) XML(w http.ResponseWriter, status int, v interface{}) {
b, err := xml.Marshal(v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
w.WriteHeader(status)
// Try to find <?xml header in first 100 bytes (just in case there're some XML comments).
findHeaderUntil := len(b)
if findHeaderUntil > 100 {
findHeaderUntil = 100
}
if !bytes.Contains(b[:findHeaderUntil], []byte("<?xml")) {
// No header found. Print it out first.
w.Write([]byte(xml.Header))
}
w.Write(b)
}
// Data writes raw bytes to the response, setting the Content-Type as
// application/octet-stream.
func (c *Context) Data(w http.ResponseWriter, status int, v []byte) {
w.Header().Set("Content-Type", "application/octet-stream")
w.WriteHeader(status)
w.Write(v)
}
// HTML writes a string to the response, setting the Content-Type as text/html.
func (c *Context) HTML(w http.ResponseWriter, status int, v string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
w.Write([]byte(v))
}
// DecodeJSON decodes json data to object
func (c *Context) DecodeJSON(r io.Reader, v interface{}) error {
defer io.Copy(ioutil.Discard, r)
return json.NewDecoder(r).Decode(v)
}
// DecodeXML decodes XML data to object
func (c *Context) DecodeXML(r io.Reader, v interface{}) error {
defer io.Copy(ioutil.Discard, r)
return xml.NewDecoder(r).Decode(v)
}
// Bind decodes a request body and binds it with v Object
func (c *Context) Bind(r *http.Request, v interface{}) error {
ct := r.Header.Get("Content-Type")
s := strings.TrimSpace(strings.Split(ct, ";")[0])
switch s {
case "application/json", "text/javascript":
return c.DecodeJSON(r.Body, v)
case "text/xml", "application/xml":
return c.DecodeXML(r.Body, v)
default:
return errors.Errorf("Unsupported Content-Type: %s", s)
}
}