-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
203 lines (168 loc) · 4.5 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
201
202
203
package winter
import (
"context"
"encoding/json"
"fmt"
"github.com/guoyk93/rg"
"go.opentelemetry.io/otel/trace"
"log"
"mime/multipart"
"net/http"
"strconv"
"sync"
"time"
)
// Bind a generic version of [Context.Bind]
//
// example:
//
// func actionValidate(c summer.Context) {
// args := summer.Bind[struct {
// Tenant string `json:"header_x_tenant"`
// Username string `json:"username"`
// Age int `json:"age,string"`
// }](c)
// _ = args.Tenant
// _ = args.Username
// _ = args.Age
// }
func Bind[T any](c Context) (o T) {
c.Bind(&o)
return
}
// Context context of an incoming request and corresponding response writer
type Context interface {
// Context extend the [context.Context] interface by proxying to [http.Request.Context]
context.Context
// Inject inject underlying [context.Context]
Inject(fn func(ctx context.Context) context.Context)
// Req returns the underlying *http.Request
Req() *http.Request
// Header returns the headers of underlying [http.ResponseWriter]
Header() http.Header
// Bind unmarshal the request data into any struct with json tags
//
// HTTP header is prefixed with "header_"
//
// HTTP query is prefixed with "query_"
//
// both JSON and Form are supported
Bind(data interface{})
// Files returns the multipart file headers
Files() map[string][]*multipart.FileHeader
// Code set the response code, can be called multiple times
Code(code int)
// Body set the response body with content type, can be called multiple times
Body(contentType string, buf []byte)
// Text set the response body to plain text
Text(s string)
// JSON set the response body to json
JSON(data interface{})
// Perform actually perform the response
// it is suggested to use in defer, recover() is included to recover from any panics
Perform()
}
type winterContext struct {
req *http.Request
rw http.ResponseWriter
buf []byte
files map[string][]*multipart.FileHeader
code int
body []byte
recvOnce *sync.Once
sendOnce *sync.Once
responseLogging bool
}
func (c *winterContext) Deadline() (deadline time.Time, ok bool) {
return c.req.Context().Deadline()
}
func (c *winterContext) Done() <-chan struct{} {
return c.req.Context().Done()
}
func (c *winterContext) Err() error {
return c.req.Context().Err()
}
func (c *winterContext) Value(key any) any {
return c.req.Context().Value(key)
}
func (c *winterContext) Inject(fn func(ctx context.Context) context.Context) {
ctx := c.req.Context()
neo := fn(ctx)
if neo != nil && neo != ctx {
c.req = c.req.WithContext(neo)
}
}
func (c *winterContext) Req() *http.Request {
return c.req
}
func (c *winterContext) Header() http.Header {
return c.rw.Header()
}
func (c *winterContext) receive() {
var m = map[string]any{}
var f = map[string][]*multipart.FileHeader{}
if err := extractRequest(m, f, c.req); err != nil {
Halt(err, HaltWithStatusCode(http.StatusBadRequest))
}
c.buf = rg.Must(json.Marshal(m))
c.files = f
}
func (c *winterContext) send() {
if c.responseLogging {
var traceID string
if sp := trace.SpanFromContext(c); sp != nil {
traceID = sp.SpanContext().TraceID().String()
}
log.Printf("trace_id=%s, code=%d; %s", traceID, c.code, string(c.body))
}
c.rw.WriteHeader(c.code)
_, _ = c.rw.Write(c.body)
}
func (c *winterContext) Bind(data interface{}) {
c.recvOnce.Do(c.receive)
rg.Must0(json.Unmarshal(c.buf, data))
}
func (c *winterContext) Files() map[string][]*multipart.FileHeader {
c.recvOnce.Do(c.receive)
return c.files
}
func (c *winterContext) Code(code int) {
c.code = code
}
func (c *winterContext) Body(contentType string, buf []byte) {
c.rw.Header().Set("Content-Type", contentType)
c.rw.Header().Set("Content-Length", strconv.Itoa(len(buf)))
c.rw.Header().Set("X-Content-Type-Options", "nosniff")
c.body = buf
}
func (c *winterContext) Text(s string) {
c.Body(ContentTypeTextPlainUTF8, []byte(s))
}
func (c *winterContext) JSON(data interface{}) {
buf := rg.Must(json.Marshal(data))
c.Body(ContentTypeApplicationJSONUTF8, buf)
}
func (c *winterContext) Perform() {
if r := recover(); r != nil {
var (
e error
ok bool
)
if e, ok = r.(error); !ok {
e = fmt.Errorf("panic: %v", r)
}
c.Code(StatusCodeFromError(e))
c.JSON(JSONBodyFromError(e))
c.responseLogging = true
}
c.sendOnce.Do(c.send)
}
func newContext(rw http.ResponseWriter, req *http.Request) *winterContext {
return &winterContext{
req: req,
rw: rw,
code: http.StatusOK,
recvOnce: &sync.Once{},
sendOnce: &sync.Once{},
}
}