nuclei/v2/pkg/output/file_output_writer.go

44 lines
956 B
Go
Raw Normal View History

package output
import (
"os"
2021-10-30 11:13:35 +00:00
"sync"
)
// fileWriter is a concurrent file based output writer.
type fileWriter struct {
2021-02-26 09:15:48 +00:00
file *os.File
2021-10-30 11:13:35 +00:00
mu sync.Mutex
}
// NewFileOutputWriter creates a new buffered writer for a file
func newFileOutputWriter(file string) (*fileWriter, error) {
output, err := os.Create(file)
if err != nil {
return nil, err
}
2021-02-26 09:15:48 +00:00
return &fileWriter{file: output}, nil
}
// WriteString writes an output to the underlying file
2021-10-30 11:19:11 +00:00
func (w *fileWriter) Write(data []byte) (int, error) {
2021-10-30 11:13:35 +00:00
w.mu.Lock()
defer w.mu.Unlock()
if _, err := w.file.Write(data); err != nil {
2021-10-30 11:19:11 +00:00
return 0, err
}
2021-10-30 11:19:11 +00:00
if _, err := w.file.Write([]byte("\n")); err != nil {
return 0, err
}
return len(data) + 1, nil
}
// Close closes the underlying writer flushing everything to disk
func (w *fileWriter) Close() error {
2021-10-30 11:13:35 +00:00
w.mu.Lock()
defer w.mu.Unlock()
//nolint:errcheck // we don't care whether sync failed or succeeded.
w.file.Sync()
return w.file.Close()
}