Skip to content

Commit

Permalink
Add QuerySignHTTPRead example (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
JinnyYi authored Sep 6, 2021
1 parent adac531 commit f83d95e
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
- [Read a file](read.go)
- [Read a range of a file](read.go)
- [Read a file with callback](read.go)
- [Read a file using signed URL](read.go)
- [Append to a new file](append.go)
- [Append to an existing file](append.go)
- [Multipart upload](multipart.go)
Expand Down
47 changes: 46 additions & 1 deletion read.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ package example

import (
"bytes"
"io/ioutil"
"log"
"net/http"
"time"

"github.com/beyondstorage/go-storage/v4/pairs"
"github.com/beyondstorage/go-storage/v4/types"
"log"
)

func ReadWhole(store types.Storager, path string) {
Expand Down Expand Up @@ -70,3 +74,44 @@ func ReadWithCallback(store types.Storager, path string) {
log.Printf("read size: %d", n)
log.Printf("read content: %s", buf.Bytes())
}

func ReadWithSignedURL(store types.Storager, path string, expire time.Duration) {
signer, ok := store.(types.StorageHTTPSigner)
if !ok {
log.Fatalf("StorageHTTPSigner unimplemented")
}

// QuerySignHTTPRead needs at least two arguments.
//
// `path` is the path of object.
// `expire` provides the time period, with type time.Duration, for which the generated req.URL is valid.
//
// QuerySignHTTPRead will return two values.
// `req` is the generated `*http.Request`, `req.URL` specifies the URL to access with signature in the query string. And `req.Header` specifies the HTTP headers included in the signature.
// `err` is the error during this operation.
req, err := signer.QuerySignHTTPRead(path, expire)
if err !=nil {
log.Fatalf("read %v: %v", path, err)
}

client := http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("send HTTP request for reading %v: %v", path, err)
}

defer func() {
err = resp.Body.Close()
if err != nil {
log.Fatalf("close HTTP response body for reading %v: %v", path, err)
}
}()

buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("read from HTTP response body for reading %v: %v", path, err)
}

log.Printf("read size: %d", resp.ContentLength)
log.Printf("read content: %s", buf)
}

0 comments on commit f83d95e

Please sign in to comment.