package gobridge import ( "bytes" "io" "sync" ) // prefixWriter 对每一行输出添加固定前缀,线程安全。 type prefixWriter struct { mu sync.Mutex w io.Writer prefix []byte buf []byte } func newPrefixWriter(w io.Writer, prefix string) *prefixWriter { return &prefixWriter{w: w, prefix: []byte(prefix)} } func (p *prefixWriter) Write(b []byte) (int, error) { p.mu.Lock() defer p.mu.Unlock() n := len(b) p.buf = append(p.buf, b...) for { idx := bytes.IndexByte(p.buf, '\n') if idx < 0 { break } line := append(p.prefix, p.buf[:idx+1]...) if _, err := p.w.Write(line); err != nil { return n, err } p.buf = p.buf[idx+1:] } return n, nil } // flush 将缓冲区中尚未以换行结尾的内容输出(进程退出时调用)。 func (p *prefixWriter) flush() { p.mu.Lock() defer p.mu.Unlock() if len(p.buf) > 0 { line := append(p.prefix, p.buf...) line = append(line, '\n') p.w.Write(line) //nolint p.buf = nil } }