add Queue.Walk()
This commit is contained in:
parent
e0018ef220
commit
7bf0709685
@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"github.com/streadway/simpleuuid"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
@ -33,6 +34,8 @@ type Queue struct {
|
||||
Dir *QueueDir
|
||||
}
|
||||
|
||||
type WalkFunc func(id string, body []byte) error
|
||||
|
||||
func (q *Queue) Add(reader io.Reader) (string, error) {
|
||||
uuid, err := simpleuuid.NewTime(time.Now())
|
||||
if err != nil {
|
||||
@ -48,6 +51,30 @@ func (q *Queue) Add(reader io.Reader) (string, error) {
|
||||
return id, err
|
||||
}
|
||||
|
||||
func (q *Queue) Walk(cb WalkFunc) error {
|
||||
return filepath.Walk(q.Path, func(path string, info os.FileInfo, err error) error {
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
body, err := ioutil.ReadAll(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return cb(filepath.Base(path), body)
|
||||
})
|
||||
}
|
||||
|
||||
func (q *Queue) AddString(body string) (string, error) {
|
||||
return q.Add(bytes.NewBufferString(body))
|
||||
}
|
||||
|
@ -30,7 +30,41 @@ func TestAdd(t *testing.T) {
|
||||
|
||||
assert.Equal(t, "BOOM", string(by))
|
||||
}
|
||||
|
||||
func TestWalk(t *testing.T) {
|
||||
q := Setup(t)
|
||||
defer q.Teardown()
|
||||
|
||||
id1, err := q.Queue.AddString("BOOM0")
|
||||
if err != nil {
|
||||
t.Fatalf("Cannot add to queue: %s", err)
|
||||
}
|
||||
|
||||
id2, err := q.Queue.AddString("BOOM1")
|
||||
if err != nil {
|
||||
t.Fatalf("Cannot add to queue: %s", err)
|
||||
}
|
||||
|
||||
seen := make(map[string]bool)
|
||||
|
||||
q.Queue.Walk(func(id string, body []byte) error {
|
||||
if err != nil {
|
||||
t.Errorf("Error reading queue data for %s: %s", id, err)
|
||||
}
|
||||
|
||||
seen[id] = true
|
||||
if id == id1 {
|
||||
assert.Equal(t, id1, id)
|
||||
} else if id == id2 {
|
||||
assert.Equal(t, id2, id)
|
||||
} else {
|
||||
t.Errorf("Weird ID: %s", id)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
assert.Equal(t, 2, len(seen))
|
||||
}
|
||||
|
||||
func TestMove(t *testing.T) {
|
||||
|
Loading…
Reference in New Issue
Block a user