Created
January 3, 2024 21:51
-
-
Save brunocalza/48c05d40545b200576bc53a9ef3586e9 to your computer and use it in GitHub Desktop.
Web3 Storage Go Upload example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
_ "embed" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"github.com/ipfs/go-cid" | |
"github.com/ipld/go-ipld-prime/datamodel" | |
cidlink "github.com/ipld/go-ipld-prime/linking/cid" | |
"github.com/multiformats/go-multihash" | |
"github.com/web3-storage/go-ucanto/core/delegation" | |
"github.com/web3-storage/go-ucanto/did" | |
"github.com/web3-storage/go-ucanto/principal/ed25519/signer" | |
"github.com/web3-storage/go-w3up/capability/storeadd" | |
"github.com/web3-storage/go-w3up/capability/uploadadd" | |
"github.com/web3-storage/go-w3up/client" | |
w3sdelegation "github.com/web3-storage/go-w3up/delegation" | |
) | |
func main() { | |
// space that the client will interact with | |
space, _ := did.Parse("did:key:z6Mkv4YhtLqTKWis8KfLWGhUEcHFPYgH97BrCZia7xsUxMWj") | |
// private key to sign UCAN invocations with | |
priv, _ := ioutil.ReadFile("private.key") | |
issuer, _ := signer.Parse(string(priv)) | |
// UCAN proof(s) that the signer can perform tasks in this space (a delegation chain) | |
prfbytes, _ := ioutil.ReadFile("proof.ucan") | |
proof, _ := w3sdelegation.ExtractProof(prfbytes) | |
data, _ := ioutil.ReadFile("hello3.car") | |
// generate the CID for the CAR | |
mh, _ := multihash.Sum(data, multihash.SHA2_256, -1) | |
link := cidlink.Link{Cid: cid.NewCidV1(0x0202, mh)} | |
rcpt, err := client.StoreAdd( | |
issuer, | |
space, | |
&storeadd.Caveat{Link: link, Size: uint64(len(data))}, | |
client.WithProofs([]delegation.Delegation{proof}), | |
) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(rcpt.Out().Ok().Status) | |
// "upload" means it needs to be uploaded, "done" means it is already done! | |
if rcpt.Out().Ok().Status == "upload" { | |
hr, _ := http.NewRequest("PUT", *rcpt.Out().Ok().Url, bytes.NewReader(data)) | |
hdr := map[string][]string{} | |
for k, v := range rcpt.Out().Ok().Headers.Values { | |
hdr[k] = []string{v} | |
} | |
hr.Header = hdr | |
hr.ContentLength = int64(len(data)) | |
httpClient := http.Client{} | |
res, _ := httpClient.Do(hr) | |
res.Body.Close() | |
} | |
fmt.Println(link.String()) | |
rcpt2, _ := client.UploadAdd( | |
issuer, | |
space, | |
&uploadadd.Caveat{Root: link, Shards: []datamodel.Link{link}}, | |
client.WithProofs([]delegation.Delegation{proof}), | |
) | |
fmt.Println(rcpt2.Out().Ok()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment