-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrender.go
66 lines (56 loc) · 1.49 KB
/
render.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
package td
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
/**
@date: 2022/3/14
**/
// Render response json
func (c *Context) Render(obj interface{}) (int, error) {
resp, _ := encodeJSON(obj)
c.ResponseWriter.Header().Set("Content-type", "application/json")
return c.ResponseWriter.Write(resp)
}
// encodeJSON
func encodeJSON(obj interface{}) ([]byte, error) {
return json.Marshal(obj)
}
// Render response json
func (c *Context) RenderString(resp string) (int, error) {
return c.ResponseWriter.Write([]byte(resp))
}
// RenderRerr response rerror
func (c *Context) RenderRerr(rerr *Rerror) (int, error) {
rerrRsp, _ := rerr.MarshalRerror()
c.ResponseWriter.Header().Set("Content-type", "application/json")
c.index = abortIndex
return c.ResponseWriter.Write(rerrRsp)
}
// Redirect request redirect
func (c *Context) Redirect(targetUrl string, code int) {
http.Redirect(c.ResponseWriter, c.Request, targetUrl, code)
}
// renderNotFound
func renderNotFound(response http.ResponseWriter, request *http.Request) {
notFoundResp, _ := RerrNotFound.MarshalRerror()
response.Header().Set("Content-type", "application/json")
response.Write(notFoundResp)
}
// Stream 方法用于发送流式响应
func (c *Context) Stream(step func(w io.Writer) bool) error {
flusher, ok := c.ResponseWriter.(http.Flusher)
if !ok {
return fmt.Errorf("stream: ResponseWriter does not implement http.Flusher")
}
for {
keepOpen := step(c.ResponseWriter)
if !keepOpen {
break
}
flusher.Flush()
}
return nil
}