-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog_other.go
94 lines (87 loc) · 1.9 KB
/
log_other.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
87
88
89
90
91
92
93
94
package jsonlog
import (
"encoding/json"
"io/ioutil"
"net/http"
"github.com/rs/zerolog"
)
//回复客户端的json
type httpReturn struct {
Status int
Msg string
Data interface{}
}
//sendJSON 发送json数据给前端
//flog 可以为nil ,用来记录日志的
//data 为数据
//status 默认由400 和 200 两个
func sendJSON(flog *zerolog.Event, w http.ResponseWriter, err error, data interface{}, status int) error {
var hr httpReturn
if status == 0 {
if err != nil {
hr.Status = 500
hr.Msg = err.Error()
} else {
hr.Status = 200
hr.Msg = "success"
}
} else {
hr.Status = status
hr.Msg = err.Error()
}
hr.Data = data
buf, err := json.Marshal(hr)
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
_, err = w.Write(buf)
if err != nil {
return err
}
if len(buf) != 0 && flog != nil {
if json.Valid(buf) {
flog.RawJSON("Response", buf)
}
}
return nil
}
//requestLog http请求的日志
func requestLog(r *http.Request, flog *zerolog.Event) []byte {
//打印请求信息
flog.Str("IP", getIP(getRealRemoteAddr(r))).
Str("Method", r.Method).
Str("URL", r.URL.String()).
Str("Referer", r.Referer()).
Str("UserAgent", r.UserAgent())
//打印 Header
headerbuf, err := json.Marshal(r.Header)
if err != nil {
flog.Str("headererror", err.Error())
}
if len(headerbuf) != 0 {
if json.Valid(headerbuf) {
flog.RawJSON("Header", headerbuf)
}
}
//打印 body 内容
bodybuf, err := ioutil.ReadAll(r.Body)
if err != nil {
flog.Str("bodyerror", err.Error())
}
if len(bodybuf) != 0 {
if json.Valid(bodybuf) {
var jsonmap interface{}
err = json.Unmarshal(bodybuf, &jsonmap)
if err != nil {
flog.Str("Unmarshalerror", err.Error())
}
bodybuf, err = json.Marshal(jsonmap)
if err != nil {
flog.Str("Marshalerror", err.Error())
}
flog.RawJSON("Request", bodybuf)
}
}
return bodybuf
}