Skip to content

Instantly share code, notes, and snippets.

@niksteff
Last active April 4, 2023 14:37
Show Gist options
  • Save niksteff/dde91e1ff17ef98a7131df48a7154447 to your computer and use it in GitHub Desktop.
Save niksteff/dde91e1ff17ef98a7131df48a7154447 to your computer and use it in GitHub Desktop.
Just a basic golang flusher implementation using bytes buffer
package buffer_test
import (
"bytes"
"log"
"sync"
"testing"
"time"
)
type Flusher struct {
mtx sync.Mutex
b [][]byte
}
func NewFlusher() Flusher {
return Flusher{
b: make([][]byte, 0),
}
}
func (f *Flusher) Write(d []byte) (int, error) {
f.mtx.Lock()
defer f.mtx.Unlock()
var written int = 0
// append to our internal storage, could also be file db whatever
f.b = append(f.b, d)
written += len(d)
return written, nil
}
// Flush our data to anywhere
func (f *Flusher) Flush() (int, error) {
f.mtx.Lock()
defer func() {
f.b = make([][]byte, 0)
f.mtx.Unlock()
}()
log.Print("simulating uploader")
data := ""
for _, d := range f.b {
data += string(d)
}
time.Sleep(500 * time.Millisecond)
log.Printf("uploaded: %s", data)
return len([]byte(data)), nil
}
func TestBuffer(t *testing.T) {
buf := bytes.Buffer{}
buf.Write([]byte(`hello, world!`)) // this is our data pool
// create a flusher that keeps track and flushes after everything is written
flusher := NewFlusher()
// write everything to a flusher, if we are done without error, upload it
_, err := buf.WriteTo(&flusher)
if err != nil {
t.Error(err)
return
}
// flush the data, which could upload or whatever
written, err := flusher.Flush()
if err != nil {
t.Error(err)
}
if written != 13 {
t.Error("mismatched number of bytes written")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment