github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/writers/writer_closer_tee.go (about)

     1  // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
     2  
     3  package writers
     4  
     5  import (
     6  	"io"
     7  )
     8  
     9  type TeeWriterCloser struct {
    10  	primaryW   io.WriteCloser
    11  	secondaryW io.WriteCloser
    12  
    13  	onFail func(err error)
    14  }
    15  
    16  func NewTeeWriterCloser(primaryW io.WriteCloser, secondaryW io.WriteCloser) *TeeWriterCloser {
    17  	return &TeeWriterCloser{
    18  		primaryW:   primaryW,
    19  		secondaryW: secondaryW,
    20  	}
    21  }
    22  
    23  func (this *TeeWriterCloser) Write(p []byte) (n int, err error) {
    24  	{
    25  		n, err = this.primaryW.Write(p)
    26  
    27  		if err != nil {
    28  			if this.onFail != nil {
    29  				this.onFail(err)
    30  			}
    31  		}
    32  	}
    33  
    34  	{
    35  		_, err2 := this.secondaryW.Write(p)
    36  		if err2 != nil {
    37  			if this.onFail != nil {
    38  				this.onFail(err2)
    39  			}
    40  		}
    41  	}
    42  
    43  	return
    44  }
    45  
    46  func (this *TeeWriterCloser) Close() error {
    47  	// 这里不关闭secondary
    48  	return this.primaryW.Close()
    49  }
    50  
    51  func (this *TeeWriterCloser) OnFail(onFail func(err error)) {
    52  	this.onFail = onFail
    53  }