| 1 | + | package utils |
| 2 | + | |
| 3 | + | import ( |
| 4 | + | "bufio" |
| 5 | + | "os" |
| 6 | + | "sync" |
| 7 | + | ) |
| 8 | + | |
| 9 | + | type Syncfile struct { |
| 10 | + | mutex *sync.Mutex |
| 11 | + | iohandler *os.File |
| 12 | + | } |
| 13 | + | |
| 14 | + | func NewSyncfile(filename string) (*Syncfile, error) { |
| 15 | + | f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) |
| 16 | + | if err != nil { |
| 17 | + | return nil, err |
| 18 | + | } |
| 19 | + | return &Syncfile{mutex: &sync.Mutex{}, iohandler: f}, nil |
| 20 | + | } |
| 21 | + | |
| 22 | + | func (sf *Syncfile) Write(content string) { |
| 23 | + | sf.mutex.Lock() |
| 24 | + | |
| 25 | + | wbuf := bufio.NewWriterSize(sf.iohandler, len(content)) |
| 26 | + | wbuf.WriteString(content) |
| 27 | + | wbuf.Flush() |
| 28 | + | |
| 29 | + | RandSleep(1) |
| 30 | + | |
| 31 | + | sf.mutex.Unlock() |
| 32 | + | } |
| 33 | + | |