-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontext.go
200 lines (171 loc) · 5.01 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 xun
import (
"net/http"
"strings"
jsoniter "github.com/json-iterator/go"
)
var (
json = jsoniter.Config{UseNumber: false}.Froze()
)
// Context is the primary structure for handling HTTP requests.
// It encapsulates the request, response, routing information, and application context.
// It offers various methods to work with request data, manipulate responses, and manage routing.
type Context struct {
Routing Routing
App *App
Response ResponseWriter
Request *http.Request
values map[string]any
}
// WriteStatus sets the HTTP status code for the response.
// It is used to return error or success status codes to the client.
// The status code will be sent to the client only once the response body is closed.
// If a status code is not set, the default status code is 200 (OK).
func (c *Context) WriteStatus(code int) {
c.Response.WriteHeader(code)
}
// WriteHeader sets a response header.
//
// If the value is an empty string, the header will be deleted.
func (c *Context) WriteHeader(key string, value string) {
if value == "" {
c.Response.Header().Del(key)
return
}
c.Response.Header().Set(key, value)
}
// View renders the specified data as a response to the client.
// It can be used to render HTML, JSON, XML, or any other type of response.
//
// The first argument is the data to be rendered. The second argument is an
// optional list of viewer names. If the list is empty, the viewer associated
// with the current route will be used. If the list is not empty, the first
// viewer in the list that matches the current request will be used.
func (c *Context) View(data any, options ...string) error {
var name string
if len(options) > 0 {
name = options[0]
}
v, ok := c.getViewer(name)
if !ok {
for _, accept := range c.Accept() {
for _, viewer := range c.Routing.Viewers {
if viewer.MimeType().Match(accept) {
v = viewer
ok = true
break
}
}
if ok {
break
}
}
}
// no any viewer is matched
if !ok {
if v == nil {
if len(c.Routing.Viewers) == 0 {
return ErrViewNotFound
}
v = c.Routing.Viewers[0] // use the first viewer as a fallback when no viewer is matched or specified by name
}
}
return v.Render(c.Response, c.Request, data)
}
// getViewer get viewer by name
func (c *Context) getViewer(name string) (Viewer, bool) {
if name == "" {
return nil, false
}
v, ok := c.App.viewers[name]
if ok {
mime := v.MimeType()
for _, accept := range c.Accept() {
if mime.Match(accept) {
return v, true
}
}
}
return v, false
}
// Redirect redirects the user to the given url.
// It uses the given status code. If the status code is not provided,
// it uses http.StatusFound (302).
func (c *Context) Redirect(url string, statusCode ...int) {
if c.App.interceptor != nil {
if c.App.interceptor.Redirect(c, url, statusCode...) {
return
}
}
c.WriteHeader("Location", url)
if len(statusCode) > 0 {
c.WriteStatus(statusCode[0])
} else {
c.WriteStatus(http.StatusFound) // 302
}
}
// AcceptLanguage returns a slice of strings representing the languages
// that the client accepts, in order of preference.
// The languages are normalized to lowercase and whitespace is trimmed.
func (c *Context) AcceptLanguage() (languages []string) {
accepted := c.Request.Header.Get("Accept-Language")
if accepted == "" {
return
}
options := strings.Split(accepted, ",")
l := len(options)
languages = make([]string, l)
for i := 0; i < l; i++ {
locale := strings.SplitN(options[i], ";", 2)
languages[i] = strings.Trim(locale[0], " ")
}
return
}
// Accept returns a slice of strings representing the media types
// that the client accepts, in order of preference.
// The media types are normalized to lowercase and whitespace is trimmed.
func (c *Context) Accept() (types []MimeType) {
accepted := c.Request.Header.Get("Accept")
if accepted == "" {
return
}
// text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
options := strings.Split(accepted, ",")
l := len(options)
types = make([]MimeType, l)
for i := 0; i < l; i++ {
if n := strings.IndexByte(options[i], ';'); n >= 0 {
types[i] = NewMimeType(strings.TrimSpace(options[i][:n]))
} else {
types[i] = NewMimeType(strings.TrimSpace(options[i]))
}
}
return
}
// RequestReferer returns the referer of the request.
func (c *Context) RequestReferer() string {
var v string
if c.App.interceptor != nil {
v = c.App.interceptor.RequestReferer(c)
}
if v == "" {
v = c.Request.Header.Get("Referer")
}
return v
}
// Get retrieves a value from the context's values map by key.
// If the values map is nil or the key does not exist, it returns nil.
func (c *Context) Get(key string) any {
if c.values == nil {
return nil
}
return c.values[key]
}
// Set assigns a value to the specified key in the context's values map.
// If the values map is nil, it initializes a new map.
func (c *Context) Set(key string, value any) {
if c.values == nil {
c.values = make(map[string]any)
}
c.values[key] = value
}