From 0269a669405d787bc99054c956333e744c7db8d5 Mon Sep 17 00:00:00 2001 From: 1fei Date: Thu, 19 Dec 2013 16:29:46 +0800 Subject: [PATCH 1/6] Update httplib.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit httplib针对的是客户端的http请求,所以应该用"Cookie",而不是"Set_Cookie" --- httplib/httplib.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/httplib/httplib.go b/httplib/httplib.go index 0817ec0a..ad51e0ad 100644 --- a/httplib/httplib.go +++ b/httplib/httplib.go @@ -90,7 +90,7 @@ func (b *BeegoHttpRequest) Header(key, value string) *BeegoHttpRequest { } func (b *BeegoHttpRequest) SetCookie(cookie *http.Cookie) *BeegoHttpRequest { - b.req.Header.Add("Set-Cookie", cookie.String()) + b.req.Header.Add("Cookie", cookie.String()) return b } From 9076ce7d17a004a53c2147d9c59f6f0129cde93a Mon Sep 17 00:00:00 2001 From: 1fei Date: Thu, 19 Dec 2013 18:13:10 +0800 Subject: [PATCH 2/6] Update conn.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用json直接初始化相关变量,代码更简单。如果把协议的首字母改大写会更简单,但不好改谢大的协议。 --- logs/conn.go | 42 +++++++++++++----------------------------- 1 file changed, 13 insertions(+), 29 deletions(-) diff --git a/logs/conn.go b/logs/conn.go index 8ad588b9..a5bc75c5 100644 --- a/logs/conn.go +++ b/logs/conn.go @@ -10,45 +10,29 @@ import ( type ConnWriter struct { lg *log.Logger innerWriter io.WriteCloser - reconnectOnMsg bool - reconnect bool - net string - addr string - level int + ReconnectOnMsg bool `json:"reconnectOnMsg"` + Reconnect bool `json:"reconnect"` + Net string `json:"net"` + Addr string `json:"addr"` + Level int `json:"level"` } func NewConn() LoggerInterface { conn := new(ConnWriter) - conn.level = LevelTrace + conn.Level = LevelTrace return conn } func (c *ConnWriter) Init(jsonconfig string) error { - var m map[string]interface{} - err := json.Unmarshal([]byte(jsonconfig), &m) + err := json.Unmarshal([]byte(jsonconfig), c) if err != nil { return err } - if rom, ok := m["reconnectOnMsg"]; ok { - c.reconnectOnMsg = rom.(bool) - } - if rc, ok := m["reconnect"]; ok { - c.reconnect = rc.(bool) - } - if nt, ok := m["net"]; ok { - c.net = nt.(string) - } - if addr, ok := m["addr"]; ok { - c.addr = addr.(string) - } - if lv, ok := m["level"]; ok { - c.level = int(lv.(float64)) - } return nil } func (c *ConnWriter) WriteMsg(msg string, level int) error { - if level < c.level { + if level < c.Level { return nil } if c.neddedConnectOnMsg() { @@ -58,7 +42,7 @@ func (c *ConnWriter) WriteMsg(msg string, level int) error { } } - if c.reconnectOnMsg { + if c.ReconnectOnMsg { defer c.innerWriter.Close() } c.lg.Println(msg) @@ -82,7 +66,7 @@ func (c *ConnWriter) connect() error { c.innerWriter = nil } - conn, err := net.Dial(c.net, c.addr) + conn, err := net.Dial(c.Net, c.Addr) if err != nil { return err } @@ -97,8 +81,8 @@ func (c *ConnWriter) connect() error { } func (c *ConnWriter) neddedConnectOnMsg() bool { - if c.reconnect { - c.reconnect = false + if c.Reconnect { + c.Reconnect = false return true } @@ -106,7 +90,7 @@ func (c *ConnWriter) neddedConnectOnMsg() bool { return true } - return c.reconnectOnMsg + return c.ReconnectOnMsg } func init() { From b68c814c50692886023337354a6683502c3242e4 Mon Sep 17 00:00:00 2001 From: 1fei Date: Thu, 19 Dec 2013 18:15:00 +0800 Subject: [PATCH 3/6] Update console.go MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用json直接初始化系统变量,代码更简单,并且便于后期扩展 --- logs/console.go | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/logs/console.go b/logs/console.go index ed03acde..0c7fc1e9 100644 --- a/logs/console.go +++ b/logs/console.go @@ -8,30 +8,26 @@ import ( type ConsoleWriter struct { lg *log.Logger - level int + Level int `json:"level"` } func NewConsole() LoggerInterface { cw := new(ConsoleWriter) cw.lg = log.New(os.Stdout, "", log.Ldate|log.Ltime) - cw.level = LevelTrace + cw.Level = LevelTrace return cw } func (c *ConsoleWriter) Init(jsonconfig string) error { - var m map[string]interface{} - err := json.Unmarshal([]byte(jsonconfig), &m) + err := json.Unmarshal([]byte(jsonconfig), c) if err != nil { return err } - if lv, ok := m["level"]; ok { - c.level = int(lv.(float64)) - } return nil } func (c *ConsoleWriter) WriteMsg(msg string, level int) error { - if level < c.level { + if level < c.Level { return nil } c.lg.Println(msg) From dcaff38cb93acefa7d9d9cbab143d4350c017da7 Mon Sep 17 00:00:00 2001 From: 1fei Date: Thu, 19 Dec 2013 18:15:46 +0800 Subject: [PATCH 4/6] Update file.go --- logs/file.go | 81 +++++++++++++++++++--------------------------------- 1 file changed, 30 insertions(+), 51 deletions(-) diff --git a/logs/file.go b/logs/file.go index 5c354b51..9cb796af 100644 --- a/logs/file.go +++ b/logs/file.go @@ -18,25 +18,25 @@ type FileLogWriter struct { *log.Logger mw *MuxWriter // The opened file - filename string + Filename string `json:"filename"` - maxlines int + Maxlines int `json:"maxlines"` maxlines_curlines int // Rotate at size - maxsize int + Maxsize int `json:"maxsize"` maxsize_cursize int // Rotate daily - daily bool - maxdays int64 + Daily bool `json:"daily"` + Maxdays int64 `json:"maxdays` daily_opendate int - rotate bool + Rotate bool `json:"rotate"` startLock sync.Mutex // Only one log can write to the file - level int + Level int `json:"level"` } type MuxWriter struct { @@ -59,13 +59,13 @@ func (l *MuxWriter) SetFd(fd *os.File) { func NewFileWriter() LoggerInterface { w := &FileLogWriter{ - filename: "", - maxlines: 1000000, - maxsize: 1 << 28, //256 MB - daily: true, - maxdays: 7, - rotate: true, - level: LevelTrace, + Filename: "", + Maxlines: 1000000, + Maxsize: 1 << 28, //256 MB + Daily: true, + Maxdays: 7, + Rotate: true, + Level: LevelTrace, } // use MuxWriter instead direct use os.File for lock write when rotate w.mw = new(MuxWriter) @@ -84,33 +84,12 @@ func NewFileWriter() LoggerInterface { // "rotate":true //} func (w *FileLogWriter) Init(jsonconfig string) error { - var m map[string]interface{} - err := json.Unmarshal([]byte(jsonconfig), &m) + err := json.Unmarshal([]byte(jsonconfig), w) if err != nil { return err } - if fn, ok := m["filename"]; !ok { + if len(w.Filename) == 0 { return errors.New("jsonconfig must have filename") - } else { - w.filename = fn.(string) - } - if ml, ok := m["maxlines"]; ok { - w.maxlines = int(ml.(float64)) - } - if ms, ok := m["maxsize"]; ok { - w.maxsize = int(ms.(float64)) - } - if dl, ok := m["daily"]; ok { - w.daily = dl.(bool) - } - if md, ok := m["maxdays"]; ok { - w.maxdays = int64(md.(float64)) - } - if rt, ok := m["rotate"]; ok { - w.rotate = rt.(bool) - } - if lv, ok := m["level"]; ok { - w.level = int(lv.(float64)) } err = w.StartLogger() return err @@ -132,11 +111,11 @@ func (w *FileLogWriter) StartLogger() error { func (w *FileLogWriter) docheck(size int) { w.startLock.Lock() defer w.startLock.Unlock() - if (w.maxlines > 0 && w.maxlines_curlines >= w.maxlines) || - (w.maxsize > 0 && w.maxsize_cursize >= w.maxsize) || - (w.daily && time.Now().Day() != w.daily_opendate) { + if (w.Maxlines > 0 && w.maxlines_curlines >= w.Maxlines) || + (w.Maxsize > 0 && w.maxsize_cursize >= w.Maxsize) || + (w.Daily && time.Now().Day() != w.daily_opendate) { if err := w.DoRotate(); err != nil { - fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) + fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err) return } } @@ -145,7 +124,7 @@ func (w *FileLogWriter) docheck(size int) { } func (w *FileLogWriter) WriteMsg(msg string, level int) error { - if level < w.level { + if level < w.Level { return nil } n := 24 + len(msg) // 24 stand for the length "2013/06/23 21:00:22 [T] " @@ -156,7 +135,7 @@ func (w *FileLogWriter) WriteMsg(msg string, level int) error { func (w *FileLogWriter) createLogFile() (*os.File, error) { // Open the log file - fd, err := os.OpenFile(w.filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) + fd, err := os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) return fd, err } @@ -169,7 +148,7 @@ func (w *FileLogWriter) initFd() error { w.maxsize_cursize = int(finfo.Size()) w.daily_opendate = time.Now().Day() if finfo.Size() > 0 { - content, err := ioutil.ReadFile(w.filename) + content, err := ioutil.ReadFile(w.Filename) if err != nil { return err } @@ -181,18 +160,18 @@ func (w *FileLogWriter) initFd() error { } func (w *FileLogWriter) DoRotate() error { - _, err := os.Lstat(w.filename) + _, err := os.Lstat(w.Filename) if err == nil { // file exists // Find the next available number num := 1 fname := "" for ; err == nil && num <= 999; num++ { - fname = w.filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num) + fname = w.Filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num) _, err = os.Lstat(fname) } // return error if the last file checked still existed if err == nil { - return fmt.Errorf("Rotate: Cannot find free log number to rename %s\n", w.filename) + return fmt.Errorf("Rotate: Cannot find free log number to rename %s\n", w.Filename) } // block Logger's io.Writer @@ -204,7 +183,7 @@ func (w *FileLogWriter) DoRotate() error { // close fd before rename // Rename the file to its newfound home - err = os.Rename(w.filename, fname) + err = os.Rename(w.Filename, fname) if err != nil { return fmt.Errorf("Rotate: %s\n", err) } @@ -222,10 +201,10 @@ func (w *FileLogWriter) DoRotate() error { } func (w *FileLogWriter) deleteOldLog() { - dir := path.Dir(w.filename) + dir := path.Dir(w.Filename) filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { - if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.maxdays) { - if strings.HasPrefix(filepath.Base(path), filepath.Base(w.filename)) { + if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.Maxdays) { + if strings.HasPrefix(filepath.Base(path), filepath.Base(w.Filename)) { os.Remove(path) } } From b87e122ac4c5b998e708cc262e085138742129ac Mon Sep 17 00:00:00 2001 From: 1fei Date: Thu, 19 Dec 2013 18:16:06 +0800 Subject: [PATCH 5/6] Update smtp.go --- logs/smtp.go | 61 +++++++++++++++------------------------------------- 1 file changed, 17 insertions(+), 44 deletions(-) diff --git a/logs/smtp.go b/logs/smtp.go index 0c34d472..228977bb 100644 --- a/logs/smtp.go +++ b/logs/smtp.go @@ -2,7 +2,6 @@ package logs import ( "encoding/json" - "errors" "fmt" "net/smtp" "strings" @@ -15,77 +14,51 @@ const ( // smtpWriter is used to send emails via given SMTP-server. type SmtpWriter struct { - username string - password string - host string - subject string - recipientAddresses []string - level int + Username string `json:"Username"` + Password string `json:"password"` + Host string `json:"Host"` + Subject string `json:"subject"` + RecipientAddresses []string `json:"sendTos"` + Level int `json:"level"` } func NewSmtpWriter() LoggerInterface { - return &SmtpWriter{level: LevelTrace} + return &SmtpWriter{Level: LevelTrace} } func (s *SmtpWriter) Init(jsonconfig string) error { - var m map[string]interface{} - err := json.Unmarshal([]byte(jsonconfig), &m) + err := json.Unmarshal([]byte(jsonconfig), s) if err != nil { return err } - if username, ok := m["username"]; !ok { - return errors.New("smtp config must have auth username") - } else if password, ok := m["password"]; !ok { - return errors.New("smtp config must have auth password") - } else if hostname, ok := m["host"]; !ok { - return errors.New("smtp config must have host like 'mail.example.com:25'") - } else if sendTos, ok := m["sendTos"]; !ok { - return errors.New("smtp config must have sendTos") - } else { - s.username = username.(string) - s.password = password.(string) - s.host = hostname.(string) - for _, v := range sendTos.([]interface{}) { - s.recipientAddresses = append(s.recipientAddresses, v.(string)) - } - } - - if subject, ok := m["subject"]; ok { - s.subject = subject.(string) - } else { - s.subject = subjectPhrase - } - if lv, ok := m["level"]; ok { - s.level = int(lv.(float64)) - } return nil } func (s *SmtpWriter) WriteMsg(msg string, level int) error { - if level < s.level { + if level < s.Level { return nil } - hp := strings.Split(s.host, ":") + hp := strings.Split(s.Host, ":") // Set up authentication information. auth := smtp.PlainAuth( "", - s.username, - s.password, + s.Username, + s.Password, hp[0], ) // Connect to the server, authenticate, set the sender and recipient, // and send the email all in one step. content_type := "Content-Type: text/plain" + "; charset=UTF-8" - mailmsg := []byte("To: " + strings.Join(s.recipientAddresses, ";") + "\r\nFrom: " + s.username + "<" + s.username + - ">\r\nSubject: " + s.subject + "\r\n" + content_type + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg) + mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.Username + "<" + s.Username + + ">\r\nSubject: " + s.Subject + "\r\n" + content_type + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg) err := smtp.SendMail( - s.host, + s.Host, auth, - s.username, - s.recipientAddresses, + s.Username, + s.RecipientAddresses, mailmsg, ) From 764bbd9897157d4f7926aedd3c76a65b177febfc Mon Sep 17 00:00:00 2001 From: slene Date: Thu, 19 Dec 2013 19:04:57 +0800 Subject: [PATCH 6/6] #390 should use filepath.Dir instead of path.Dir for. --- cache/file.go | 12 ++++++------ logs/file.go | 3 +-- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/cache/file.go b/cache/file.go index 8508c1d1..4612ee16 100644 --- a/cache/file.go +++ b/cache/file.go @@ -14,7 +14,7 @@ import ( "fmt" "io" "os" - "path" + "path/filepath" "reflect" "strconv" "time" @@ -79,8 +79,8 @@ func (this *FileCache) StartAndGC(config string) error { } func (this *FileCache) Init() { - app := path.Dir(os.Args[0]) - this.CachePath = path.Join(app, this.CachePath) + app := filepath.Dir(os.Args[0]) + this.CachePath = filepath.Join(app, this.CachePath) ok, err := exists(this.CachePath) if err != nil { // print error //fmt.Println(err) @@ -102,9 +102,9 @@ func (this *FileCache) getCacheFileName(key string) string { //fmt.Println("md5" , keyMd5); switch this.DirectoryLevel { case 2: - cachePath = path.Join(cachePath, keyMd5[0:2], keyMd5[2:4]) + cachePath = filepath.Join(cachePath, keyMd5[0:2], keyMd5[2:4]) case 1: - cachePath = path.Join(cachePath, keyMd5[0:2]) + cachePath = filepath.Join(cachePath, keyMd5[0:2]) } ok, err := exists(cachePath) @@ -116,7 +116,7 @@ func (this *FileCache) getCacheFileName(key string) string { //fmt.Println(err); } } - return path.Join(cachePath, fmt.Sprintf("%s%s", keyMd5, this.FileSuffix)) + return filepath.Join(cachePath, fmt.Sprintf("%s%s", keyMd5, this.FileSuffix)) } func (this *FileCache) Get(key string) interface{} { diff --git a/logs/file.go b/logs/file.go index 9cb796af..e19c6c7f 100644 --- a/logs/file.go +++ b/logs/file.go @@ -7,7 +7,6 @@ import ( "io/ioutil" "log" "os" - "path" "path/filepath" "strings" "sync" @@ -201,7 +200,7 @@ func (w *FileLogWriter) DoRotate() error { } func (w *FileLogWriter) deleteOldLog() { - dir := path.Dir(w.Filename) + dir := filepath.Dir(w.Filename) filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.Maxdays) { if strings.HasPrefix(filepath.Base(path), filepath.Base(w.Filename)) {