diff --git a/README.md b/README.md index 332a19a..2c2e793 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,8 @@ package main import ( "io/fs" "os" + "fmt" + "context" "github.com/web3-storage/go-w3s-client" ) diff --git a/put.go b/put.go index a79eb90..9aa2e99 100644 --- a/put.go +++ b/put.go @@ -92,6 +92,7 @@ func (c *client) PutCar(ctx context.Context, car io.Reader) (cid.Cid, error) { var root cid.Cid for { r, err := spltr.Next() + if err != nil { if err == io.EOF { break @@ -110,8 +111,8 @@ func (c *client) PutCar(ctx context.Context, car io.Reader) (cid.Cid, error) { return root, nil } -// TODO: retry func (c *client) sendCar(ctx context.Context, r io.Reader) (cid.Cid, error) { + req, err := http.NewRequestWithContext(ctx, "POST", c.cfg.endpoint+"/car", r) if err != nil { return cid.Undef, err @@ -124,7 +125,11 @@ func (c *client) sendCar(ctx context.Context, r io.Reader) (cid.Cid, error) { return cid.Undef, err } if res.StatusCode != 200 { - return cid.Undef, fmt.Errorf("unexpected response status: %d", res.StatusCode) + + //retry on failure + fmt.Printf("unexpected response status: %d, retrying..\n", res.StatusCode) + c.sendCar(ctx, r) + } d := json.NewDecoder(res.Body) var out struct { diff --git a/w3scli/w3scli.go b/w3scli/w3scli.go new file mode 100644 index 0000000..ca5c0e5 --- /dev/null +++ b/w3scli/w3scli.go @@ -0,0 +1,44 @@ +package main + +import ( + "context" + "fmt" + "io/fs" + "os" + "github.com/ipfs/go-cid" + "github.com/web3-storage/go-w3s-client" + +) + +// Usage: +// TOKEN="API_TOKEN" go run ./w3scli.go +func main() { + + + c, err := w3s.NewClient( + w3s.WithEndpoint(os.Getenv("ENDPOINT")), + w3s.WithToken(os.Getenv("TOKEN")), + ) + if err != nil { + panic(err) + } + + arg := os.Args[1] + file, err := os.Open(arg) + if err != nil { + panic(err) + } + + putFile(c, file) + +} + + +func putFile(c w3s.Client, f fs.File, opts ...w3s.PutOption) cid.Cid { + cid, err := c.Put(context.Background(), f, opts...) + if err != nil { + panic(err) + } + fmt.Printf("https://%v.ipfs.dweb.link\n", cid) + return cid +}