/
response.go
76 lines (57 loc) · 1.77 KB
/
response.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
package webfmwk
import "log/slog"
type (
// Header represent a header in a string key:value form.
Header [2]string
// SendResponse interface is used to reponde content to the client.
SendResponse interface {
JSONResponse
// SendResponse create & send a response according to the parameters.
SendResponse(op int, content []byte, headers ...Header) error
// SetHeader set the header of the http response.
SetHeaders(headers ...Header)
// SetHeader set the k header to value v.
SetHeader(k, v string)
// SetContentType set the Content-Type to v.
SetContentType(v string)
// SetContentType set the Content-Type to v.
SetStatusCode(code int)
// IsPretty toggle the compact output mode.
IsPretty() bool
}
)
// SetHeaders implement Context
func (c *icontext) SetHeaders(headers ...Header) {
c.setHeaders(headers...)
}
// SetHeaders implement Context
func (c *icontext) SetHeader(k, v string) {
c.setHeaders(Header{k, v})
}
// IsPretty implement Context
func (c *icontext) IsPretty() bool {
return c.QueryArgs().Has(_prettyTag)
}
// SendResponse implement Context
func (c *icontext) SendResponse(statusCode int, content []byte, headers ...Header) error {
c.setHeaders(headers...)
return c.response(statusCode, content)
}
// setHeader set the header of the holded http.ResponseWriter
func (c *icontext) setHeaders(headers ...Header) {
for _, h := range headers {
key, val := h[0], h[1]
if key == "" || val == "" {
c.slog.Warn("can't set header: empty value", slog.String("key", key), slog.String("val", val))
return
}
c.Response.Header.Set(key, val)
}
}
// response answer the client
// IDEA: add toggler `logReponse` ?
func (c *icontext) response(statusCode int, content []byte) error {
c.SetStatusCode(statusCode)
c.SetBody(content)
return nil
}