initial implementation of publish, pin, and retrieve functions
imw imw@0x539.lol
Fri, 07 Dec 2018 14:27:38 +0100
2 files changed,
85 insertions(+),
0 deletions(-)
A
data/data.go
@@ -0,0 +1,51 @@
+package data + +import ( + "os" + "fmt" + "bytes" + "io/ioutil" + shell "github.com/ipfs/go-ipfs-api" +) + +type votePacket struct { + PID uint + Nullifier string + Vote string + Franchise string +} + +func publish(object []byte) (string) { + sh := shell.NewShell("localhost:5001") + cid, err := sh.Add(bytes.NewBuffer(object)) + if err != nil { + fmt.Fprintf(os.Stderr, "error: %s", err) + os.Exit(1) + } + return cid +} + +func pin(path string) { + sh := shell.NewShell("localhost:5001") + err := sh.Pin(path) + if err != nil{ + fmt.Fprintf(os.Stderr, "error: %s", err) + os.Exit(1) + } +} + + +func retrieve(hash string) ([]byte){ + sh := shell.NewShell("localhost:5001") + reader, err := sh.Cat(hash) + if err != nil { + fmt.Fprintf(os.Stderr, "error: %s", err) + os.Exit(1) + } + content, err := ioutil.ReadAll(reader) + if err != nil { + fmt.Fprintf(os.Stderr, "error: %s", err) + os.Exit(1) + } + return content +}
A
data/data_test.go
@@ -0,0 +1,34 @@
+package data + +import ( + "testing" + "fmt" + "encoding/json" + "strings" +) + +func TestPublishAndRetrieve(t *testing.T) { + t.Log("Testing adding json") + + exampleVote := votePacket{ + 000001, + "12309801002", + "nynnynnnynnnyy", + "132498-0-02103908", + } + + testObject, err := json.Marshal(exampleVote) + if err != nil { + t.Errorf("Bad test JSON: %s", err) + } + prepub := string(testObject) + + hash := publish(testObject) + content := retrieve(hash) + postpub := string(content) + //fmt.Println(hash) + //fmt.Println(string(content)) + if strings.Compare(prepub,postpub) != 0 { + t.Errorf("Published file doesn't match. Expected:\n %s \n Got: \n %s \n", prepub, postpub) + } +}