From 9076ce7d17a004a53c2147d9c59f6f0129cde93a Mon Sep 17 00:00:00 2001 From: 1fei Date: Thu, 19 Dec 2013 18:13:10 +0800 Subject: [PATCH] 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() {