-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmouthpiece.go
86 lines (71 loc) · 1.67 KB
/
mouthpiece.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
package easyhttp
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
// ErrorStatus 返回包含不同状态的错误信息
type ErrorStatus interface {
Status() int
}
// Mouthpiece 返回response的结果,记录错误日志
type Mouthpiece struct {
resp http.ResponseWriter
Err error `json:"-"`
Message string `json:"message"`
Status int `json:"status"`
Data interface{} `json:"data,omitempty"`
}
// NewMouthpiece 创建传话筒
func NewMouthpiece(resp http.ResponseWriter) (mp *Mouthpiece) {
mp = new(Mouthpiece)
mp.resp = resp
mp.Status = -1
return
}
// SetError 设置错误信息
func (mp *Mouthpiece) SetError(err error) {
mp.Err = err
}
// Convey 将执行结果使用http response返回
func (mp *Mouthpiece) String() (strContent string) {
jsonContent, err := json.Marshal(mp)
if err != nil {
strContent = err.Error()
}
strContent = string(jsonContent)
strContent = fmt.Sprintf("准备Response:%s", strContent)
return
}
// Convey 将执行结果使用http response返回
func (mp *Mouthpiece) Convey() (err error) {
if mp.Err != nil {
if se, ok := mp.Err.(ErrorStatus); ok {
mp.Status = se.Status()
} else {
mp.Status = -1
}
mp.Message = mp.Err.Error()
} else {
mp.Status = 0
mp.Message = "OK"
}
err = Response(mp.resp, mp)
return
}
// Response 将结果打包成json返回给http
func Response(resp http.ResponseWriter, result interface{}) (err error) {
respMsg, err := json.Marshal(result)
if err != nil {
return
}
respStr := string(respMsg)
replacer := strings.NewReplacer(
"\\u0026", "&",
"\\u003c", "<",
"\\u003e", ">")
respMsg = []byte(replacer.Replace(respStr))
_, err = resp.Write(respMsg)
return
}