Browse Source

initial implementation of publish, pin, and retrieve functions

ipfs_initial_approach
imw 5 years ago
parent
commit
99a71873b8
2 changed files with 85 additions and 0 deletions
  1. +51
    -0
      data/data.go
  2. +34
    -0
      data/data_test.go

+ 51
- 0
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
}

+ 34
- 0
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)
}
}

Loading…
Cancel
Save