1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- /*
- *
- 日志过滤器
- 记录网站所有访问和请求
- 2015-7-2
- 任政
- *
- */
- package filter
- import (
- "app.yhyue.com/moapp/jybase/go-xweb/xweb"
- "app.yhyue.com/moapp/message/db"
- "encoding/json"
- "net"
- "net/http"
- "strings"
- "time"
- "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
- )
- // 日志过滤器
- type logfilter struct {
- App *xweb.App
- }
- // 继承过滤器方法
- func (l *logfilter) Do(w http.ResponseWriter, req *http.Request) bool {
- session := l.App.SessionManager.Session(req, w)
- go addLog(l, session, req)
- return true
- }
- // 用线程处理,增加日志
- func addLog(l *logfilter, session *httpsession.Session, req *http.Request) {
- timeNow := time.Now()
- md, _ := json.Marshal(req.Form)
- logs := map[string]interface{}{
- "createtime": timeNow,
- "ip": GetIp(req),
- "refer": req.Referer(),
- "year": timeNow.Year(),
- "month": timeNow.Month(),
- "day": timeNow.Day(),
- "hour": timeNow.Hour(),
- "minutes": timeNow.Minute(),
- "describe": string(md),
- "client": req.Header.Get("user-agent"),
- "method": req.Method,
- "url": req.RequestURI,
- }
- if session.Get("userId") != nil {
- logs["userid"] = session.Get("userId")
- logs["nickname"] = session.Get("s_nickname")
- }
- db.MgoLog.Save("jymessage_logs", logs)
- }
- // 获取请求ip
- func GetIp(req *http.Request) string {
- if req == nil {
- return ""
- }
- ip_for := req.Header.Get("x-forwarded-for")
- ip_client := req.Header.Get("http_client_ip")
- ip_addr := req.Header.Get("Remote_addr")
- un := "unknown"
- if (ip_for != un) && (len(strings.TrimSpace(ip_for)) > 0) {
- return ip_for
- }
- if (ip_client != un) && (len(strings.TrimSpace(ip_client)) > 0) {
- return ip_client
- }
- if (ip_addr != un) && (len(strings.TrimSpace(ip_addr)) > 0) {
- return ip_addr
- }
- ip, _, _ := net.SplitHostPort(req.RemoteAddr)
- return ip
- }
|