-
Notifications
You must be signed in to change notification settings - Fork 4
/
context.go
200 lines (157 loc) · 3.98 KB
/
context.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
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package httpway
import (
"io"
"net/http"
"sync/atomic"
"bufio"
"fmt"
"github.com/julienschmidt/httprouter"
"net"
)
var requestId uint64 = 0
//get the context associated with the request
func GetContext(r *http.Request) *Context {
crc, ok := r.Body.(contextReadCloser)
if !ok {
return nil
}
return crc.ctx()
}
//this is the context that is created for each request
type Context struct {
data map[string]interface{}
logger Logger
session Session
statusCode int
transferedBytes uint64
params *httprouter.Params
payload interface{}
handlers *[]Handler
runNextHandlerIdx int
}
//execute the next middleware
func (c *Context) Next(w http.ResponseWriter, r *http.Request) {
c.runNextHandlerIdx--
if c.runNextHandlerIdx < 0 {
panic("No next middleware, don't call it in final handler")
}
(*c.handlers)[c.runNextHandlerIdx](w, r)
}
//set a key on context
func (c *Context) Set(key string, value interface{}) {
c.data[key] = value
}
//get a key from context and if was set
func (c *Context) GetOk(key string) (value interface{}, found bool) {
value, found = c.data[key]
return
}
//get a a key from the context
func (c *Context) Get(key string) interface{} {
return c.data[key]
}
//check if a key was set on the context
func (c *Context) Has(key string) bool {
_, has := c.data[key]
return has
}
func (c *Context) StatusCode() int {
return c.statusCode
}
func (c *Context) TransferedBytes() uint64 {
return c.transferedBytes
}
//returns the logger associated with the request
func (c *Context) Log() Logger {
if c.logger == nil {
panic("No logger set")
}
return c.logger
}
//check if log is enabled
func (c *Context) HasLog() bool {
if c.logger == nil {
return false
}
return true
}
//returns the session associated with the request
func (c *Context) Session() Session {
if c.session == nil {
panic("No session set")
}
return c.session
}
//check if session is enabled
func (c *Context) HasSession() bool {
if c.session == nil {
return false
}
return true
}
//get the param from url
func (c *Context) ParamByName(name string) string {
return c.params.ByName(name)
}
//get the parsed body payload
func (c *Context) Payload() interface{} {
return c.payload
}
//create context with middlewares chain for the request
func CreateContext(router *Router, w http.ResponseWriter, r *http.Request, handlers *[]Handler, handlersLen *int, pr *httprouter.Params) http.ResponseWriter {
crc := &contextReadClose{
ReadCloser: r.Body,
ctxObj: &Context{
data: make(map[string]interface{}),
handlers: handlers,
runNextHandlerIdx: *handlersLen,
params: pr,
},
}
crc.ctxObj.logger = &internalLogger{router.Logger, atomic.AddUint64(&requestId, 1), ""}
r.Body = crc
w = &internalResponseWriter{w, crc.ctxObj}
if router.SessionManager != nil {
crc.ctxObj.session = router.SessionManager.Get(w, r, crc.ctxObj.logger)
if crc.ctxObj.session.Username() != "" {
crc.ctxObj.logger.(*internalLogger).prefix = crc.ctxObj.session.Username()
}
}
return w
}
type contextReadCloser interface {
io.ReadCloser
ctx() *Context
}
type contextReadClose struct {
io.ReadCloser
ctxObj *Context
}
func (crc *contextReadClose) ctx() *Context {
return crc.ctxObj
}
type internalResponseWriter struct {
http.ResponseWriter
ctx *Context
}
func (irw *internalResponseWriter) Write(b []byte) (n int, err error) {
if irw.ctx.statusCode == 0 {
irw.ctx.statusCode = 200
}
n, err = irw.ResponseWriter.Write(b)
irw.ctx.transferedBytes += uint64(n)
return
}
func (irw *internalResponseWriter) WriteHeader(status int) {
if irw.ctx.statusCode == 0 {
irw.ctx.statusCode = status
}
irw.ResponseWriter.WriteHeader(status)
}
func (irw *internalResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hij, ok := irw.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("Unable to Hijack the connection %T doesn't implement Hijack", irw.ResponseWriter)
}
return hij.Hijack()
}