github.com/coyove/common@v0.0.0-20240403014525-f70e643f9de8/logg/buffer.go (about) 1 package logg 2 3 import ( 4 "bytes" 5 ) 6 7 type csvbuffer struct { 8 bytes.Buffer 9 } 10 11 func (b *csvbuffer) Write(msgs ...string) { 12 tmp := bytes.Buffer{} 13 for _, msg := range msgs { 14 quote := false 15 tmp.Reset() 16 17 for _, r := range msg { 18 switch r { 19 case '\r': 20 continue 21 case ',', '\n': 22 tmp.WriteRune(r) 23 quote = true 24 case '"': 25 tmp.WriteString("\"\"") 26 quote = true 27 default: 28 tmp.WriteRune(r) 29 } 30 } 31 32 if quote { 33 b.Buffer.WriteRune('"') 34 } 35 b.Buffer.Write(tmp.Bytes()) 36 if quote { 37 b.Buffer.WriteRune('"') 38 } 39 b.Buffer.WriteRune(',') 40 } 41 } 42 43 func (b *csvbuffer) NewLine() { 44 if b.Len() > 0 && b.Bytes()[b.Len()-1] == ',' { 45 b.Truncate(b.Len() - 1) 46 } 47 b.WriteRune('\n') 48 }