Skip to content

Commit

Permalink
修复日志Writer为nil的bug
Browse files Browse the repository at this point in the history
  • Loading branch information
injoyai committed Jan 16, 2024
1 parent 4bacd90 commit 4dbbd45
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
19 changes: 19 additions & 0 deletions dial/dial_websicket.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,25 @@ import (

//================================Websocket================================

type WebsocketConfig struct {
Dial *websocket.Dialer
Url string
Header http.Header
}

func (this *WebsocketConfig) DialFunc() (io.ReadWriteCloser, string, error) {
if this.Dial == nil {
this.Dial = websocket.DefaultDialer
}
c, _, err := this.Dial.Dial(this.Url, this.Header)
return &WebsocketClient{Conn: c}, func() string {
if u, err := gourl.Parse(this.Url); err == nil {
return u.Path
}
return this.Url
}(), err
}

// Websocket 连接
func Websocket(url string, header http.Header) (io.ReadWriteCloser, string, error) {
c, _, err := websocket.DefaultDialer.Dial(url, header)
Expand Down
18 changes: 18 additions & 0 deletions io_func.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,3 +235,21 @@ func (this TryChan) Write(p []byte) (int, error) {
return 0, nil
}
}

//====================

// Count 统计写入字节数量
type Count struct {
io.Writer
count int64
}

func (this *Count) Count() int64 {
return this.count
}

func (this *Count) Write(p []byte) (int, error) {
n, err := this.Writer.Write(p)
this.count += int64(n)
return n, err
}
6 changes: 6 additions & 0 deletions io_log.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@ func (this *logger) Errorf(format string, v ...interface{}) {

// NewLoggerWithWriter 新建输出到writer的日志
func NewLoggerWithWriter(w Writer) Logger {
if w == nil {
w = &null{}
}
return &logWriter{w}
}

Expand Down Expand Up @@ -174,6 +177,9 @@ func (p logWriter) Infof(format string, v ...interface{}) { p.printf(LevelInfo,
func (p logWriter) Errorf(format string, v ...interface{}) { p.printf(LevelError, format, v...) }

func (p logWriter) printf(level Level, format string, v ...interface{}) {
if p.Writer == nil {
return
}
timeStr := time.Now().Format("2006-01-02 15:04:05 ")
_, err := p.Writer.Write([]byte(fmt.Sprintf(timeStr+"["+level.Name()+"] "+format, v...)))
logs.PrintErr(err)
Expand Down

0 comments on commit 4dbbd45

Please sign in to comment.