/
resp.go
executable file
·51 lines (44 loc) · 1.1 KB
/
resp.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
package util
import (
"encoding/json"
"fmt"
"log"
)
// RespMsg : http响应数据的通用结构
type RespMsg struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
// NewRespMsg : 生成response对象
func NewRespMsg(code int, msg string, data interface{}) *RespMsg {
return &RespMsg{
Code: code,
Msg: msg,
Data: data,
}
}
// JSONBytes : 对象转json格式的二进制数组
func (resp *RespMsg) JSONBytes() []byte {
r, err := json.Marshal(resp)
if err != nil {
log.Println(err)
}
return r
}
// JSONString : 对象转json格式的string
func (resp *RespMsg) JSONString() string {
r, err := json.Marshal(resp)
if err != nil {
log.Println(err)
}
return string(r)
}
// GenSimpleRespStream : 只包含code和message的响应体([]byte)
func GenSimpleRespStream(code int, msg string) []byte {
return []byte(fmt.Sprintf(`{"code":%d,"msg":"%s"}`, code, msg))
}
// GenSimpleRespString : 只包含code和message的响应体(string)
func GenSimpleRespString(code int, msg string) string {
return fmt.Sprintf(`{"code":%d,"msg":"%s"}`, code, msg)
}