-
Notifications
You must be signed in to change notification settings - Fork 9
/
ret.go
executable file
·76 lines (67 loc) · 2.22 KB
/
ret.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 app
import (
"encoding/json"
"fmt"
"net/http"
"time"
)
const (
OK = 0
NotFoundServer = 1001
NotFound = 65531
TooLong = 65532
AuthErr = 65533
ParamErr = 65534
InternalErr = 65535
OverQuotaApicall = 65536
OverQuotaPush = 65537
DeleteUser = 65538
LoginErr = 65539
)
// 响应基础结构.
type baseResponse struct {
Ret int `json:"ret"`
ErrMsg string `json:"errMsg"`
}
// retWrite marshal the result and write to client(get).
func RetWrite(w http.ResponseWriter, r *http.Request, res map[string]interface{}, callback string, start time.Time) {
data, err := json.Marshal(res)
if err != nil {
logger.Errorf("json.Marshal(\"%v\") error(%v)", res, err)
return
}
dataStr := ""
if callback == "" {
// Normal json
dataStr = string(data)
} else {
// Jsonp
dataStr = fmt.Sprintf("%s(%s)", callback, string(data))
}
if n, err := w.Write([]byte(dataStr)); err != nil {
logger.Errorf("w.Write(\"%s\") error(%v)", dataStr, err)
} else {
logger.Tracef("w.Write(\"%s\") write %d bytes", dataStr, n)
}
logger.Tracef("req: \"%s\", res:\"%s\", ip:\"%s\", time:\"%fs\"", r.URL.String(), dataStr, r.RemoteAddr, time.Now().Sub(start).Seconds())
}
// retPWrite marshal the result and write to client(post).
func RetPWrite(w http.ResponseWriter, r *http.Request, res map[string]interface{}, body *string, start time.Time) {
data, err := json.Marshal(res)
if err != nil {
logger.Errorf("json.Marshal(\"%v\") error(%v)", res, err)
return
}
dataStr := string(data)
if n, err := w.Write([]byte(dataStr)); err != nil {
logger.Errorf("w.Write(\"%s\") error(%v)", dataStr, err)
} else {
logger.Tracef("w.Write(\"%s\") write %d bytes", dataStr, n)
}
logger.Tracef("req: \"%s\", post: \"%s\", res:\"%s\", ip:\"%s\", time:\"%fs\"", r.URL.String(), *body, dataStr, r.RemoteAddr, time.Now().Sub(start).Seconds())
}
// 带 Content-Type=application/json 头 写 JSON 数据,为了保持原有 gopush-cluster 的兼容性,所以新加了这个函数.
func RetPWriteJSON(w http.ResponseWriter, r *http.Request, res map[string]interface{}, body *string, start time.Time) {
w.Header().Set("Content-Type", "application/json")
RetPWrite(w, r, res, body, start)
}