-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend.go
74 lines (66 loc) · 1.62 KB
/
backend.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"bytes"
"context"
"encoding/gob"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
pb "github.com/nhite/pb-backend"
)
type backend struct {
workingDir string
permission os.FileMode
fileExtension string
}
func (b *backend) Store(stream pb.Backend_StoreServer) error {
if debug {
log.Println("[store] =>")
}
body, err := stream.Recv()
if err == io.EOF || err == nil {
if debug {
log.Printf("[store] ==> received flow with ID %v", body.GetID().GetID())
}
// By now let's use a gobencoding for flexibility
var content bytes.Buffer
// Create an encoder and send a value.
enc := gob.NewEncoder(&content)
err = enc.Encode(body)
if err != nil {
return err
}
err := ioutil.WriteFile(filepath.Join(b.workingDir, body.GetID().GetID()+b.fileExtension), content.Bytes(), b.permission)
if err != nil {
return err
}
if debug {
log.Printf("[store] ==> content written in %v", filepath.Join(b.workingDir, body.GetID().GetID()+b.fileExtension))
}
}
if err != nil {
return err
}
return stream.SendAndClose(&pb.Error{})
}
func (b *backend) Fetch(id *pb.ElementID, stream pb.Backend_FetchServer) error {
var element *pb.Element
body, err := ioutil.ReadFile(filepath.Join(b.workingDir, id.GetID()+b.fileExtension))
if err != nil {
return err
}
content := bytes.NewBuffer(body)
// Create a decoder and receive a value.
dec := gob.NewDecoder(content)
err = dec.Decode(&element)
if err != nil {
return err
}
return stream.Send(element)
}
// TODO implement the list function
func (b *backend) List(context.Context, *pb.Pagination) (*pb.Elements, error) {
return nil, nil
}