-
Notifications
You must be signed in to change notification settings - Fork 5
/
write.go
95 lines (80 loc) · 2.62 KB
/
write.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package example
import (
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"time"
"go.beyondstorage.io/v5/pairs"
"go.beyondstorage.io/v5/pkg/randbytes"
"go.beyondstorage.io/v5/types"
)
func WriteData(store types.Storager, path string) {
// content to write
size := rand.Int63n(4 * 1024 * 1024)
r := io.LimitReader(randbytes.NewRand(), size)
// Write needs at least three arguments.
// `path` is the path of object.
// `r` is io.Reader instance for reading the data for uploading.
// `size` is the length, in bytes, of the data for uploading.
//
// Write will return two values.
// `n` is the size of write operation.
// `err` is the error during this operation.
n, err := store.Write(path, r, size)
if err != nil {
log.Fatalf("write %v: %v", path, err)
}
log.Printf("write size: %d", n)
}
func WriteWithCallback(store types.Storager, path string) {
// content to write
size := rand.Int63n(4 * 1024 * 1024)
r := io.LimitReader(randbytes.NewRand(), size)
cur := int64(0)
fn := func(bs []byte) {
cur += int64(len(bs))
log.Printf("write %d bytes already", cur)
}
// If IoCallback is specified, the storage will call it in every I/O operation.
// User could use this feature to implement progress bar.
n, err := store.Write(path, r, size, pairs.WithIoCallback(fn))
if err != nil {
log.Fatalf("write %v: %v", path, err)
}
log.Printf("write size: %d", n)
}
func WriteWithSignedURL(store types.Storager, path string, expire time.Duration) {
signer, ok := store.(types.StorageHTTPSigner)
if !ok {
log.Fatalf("StorageHTTPSigner unimplemented")
}
size := rand.Int63n(4 * 1024 * 1024)
r := io.LimitReader(randbytes.NewRand(), size)
// QuerySignHTTPWrite needs at least three arguments.
// `path` is the path of object.
// `size` is the length, in bytes, of the data for uploading.
// `expire` provides the time period, with type time.Duration, for which the generated req.URL is valid.
//
// QuerySignHTTPWrite will return two values.
//
// `req` is the generated `*http.Request`:
// `req.URL` specifies the URL to access with signature in the query string.
// `req.Header` specifies the HTTP headers included in the signature.
// `req.ContentLength` records the length of the associated content, the value equals to `size`.
//
// `err` is the error during this operation.
req, err := signer.QuerySignHTTPWrite(path, size, expire)
if err != nil {
log.Fatalf("write %v: %v", path, err)
}
// Set request body.
req.Body = ioutil.NopCloser(r)
client := http.Client{}
_, err = client.Do(req)
if err != nil {
log.Fatalf("send HTTP request for writing %v: %v", path, err)
}
log.Printf("write size: %d", size)
}