-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzero_render.go
More file actions
73 lines (64 loc) · 1.49 KB
/
Copy pathzero_render.go
File metadata and controls
73 lines (64 loc) · 1.49 KB
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
package render
import (
"errors"
"fmt"
jsoniter "github.com/json-iterator/go"
"github.com/zeromicro/go-zero/core/logx"
"net/http"
)
// rsp
// @Description:
type rsp struct {
Code int `json:"code"`
Msg string `json:"msg,omitempty"`
Data any `json:"data,omitempty"`
}
// ResponseJson
//
// @Description:
// @param w
// @param resp
// @param err
func ResponseJson(w http.ResponseWriter, resp interface{}, err error) {
var body rsp
if err != nil {
body.Code = -1
body.Msg = err.Error()
} else {
body.Data = resp
}
//do write json
err = doWriteJson(w, http.StatusOK, &body)
if err != nil {
logx.Errorf("doWriteJson err:%s", err)
return
}
}
// doWriteJson
//
// @Description:
// @param w
// @param statusCode
// @param v
// @return error
func doWriteJson(w http.ResponseWriter, statusCode int, v any) error {
bs, err := jsoniter.Marshal(v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return fmt.Errorf("marshal json failed, error: %w", err)
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(statusCode)
//write data
if n, err := w.Write(bs); err != nil {
// http.ErrHandlerTimeout has been handled by http.TimeoutHandler,
// so it's ignored here.
if !errors.Is(err, http.ErrHandlerTimeout) {
return fmt.Errorf("write response failed, error: %w", err)
}
} else if n < len(bs) {
return fmt.Errorf("actual bytes: %d, written bytes: %d", len(bs), n)
}
//all bytes data write to client DONE !
return nil
}