You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
1.4 KiB

  1. package writer
  2. import (
  3. "bytes"
  4. "io"
  5. "sync"
  6. )
  7. type WriterInterface interface {
  8. io.Writer
  9. Truncate()
  10. DumpOut()
  11. DumpOutWithHeader(header string)
  12. Bytes() []byte
  13. }
  14. type Writer struct {
  15. buffer *bytes.Buffer
  16. outWriter io.Writer
  17. lock *sync.Mutex
  18. stream bool
  19. redirector io.Writer
  20. }
  21. func New(outWriter io.Writer) *Writer {
  22. return &Writer{
  23. buffer: &bytes.Buffer{},
  24. lock: &sync.Mutex{},
  25. outWriter: outWriter,
  26. stream: true,
  27. }
  28. }
  29. func (w *Writer) AndRedirectTo(writer io.Writer) {
  30. w.redirector = writer
  31. }
  32. func (w *Writer) SetStream(stream bool) {
  33. w.lock.Lock()
  34. defer w.lock.Unlock()
  35. w.stream = stream
  36. }
  37. func (w *Writer) Write(b []byte) (n int, err error) {
  38. w.lock.Lock()
  39. defer w.lock.Unlock()
  40. n, err = w.buffer.Write(b)
  41. if w.redirector != nil {
  42. w.redirector.Write(b)
  43. }
  44. if w.stream {
  45. return w.outWriter.Write(b)
  46. }
  47. return n, err
  48. }
  49. func (w *Writer) Truncate() {
  50. w.lock.Lock()
  51. defer w.lock.Unlock()
  52. w.buffer.Reset()
  53. }
  54. func (w *Writer) DumpOut() {
  55. w.lock.Lock()
  56. defer w.lock.Unlock()
  57. if !w.stream {
  58. w.buffer.WriteTo(w.outWriter)
  59. }
  60. }
  61. func (w *Writer) Bytes() []byte {
  62. w.lock.Lock()
  63. defer w.lock.Unlock()
  64. b := w.buffer.Bytes()
  65. copied := make([]byte, len(b))
  66. copy(copied, b)
  67. return copied
  68. }
  69. func (w *Writer) DumpOutWithHeader(header string) {
  70. w.lock.Lock()
  71. defer w.lock.Unlock()
  72. if !w.stream && w.buffer.Len() > 0 {
  73. w.outWriter.Write([]byte(header))
  74. w.buffer.WriteTo(w.outWriter)
  75. }
  76. }