-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsblob.go
79 lines (66 loc) · 2.21 KB
/
jsblob.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
/*
Package jsblob provides GopherJS bindings for the JavaScript Blob objects.
Read more about JavaScript Blobs here: https://developer.mozilla.org/en-US/docs/Web/API/Blob
A js.Object containing an existing Blob can be cast to a Blob object as follows:
nativeBlob := js.Global.Get("Blob").New([]string{"some blobby data"})
blob := jsblob.Blob{*nativeBlob}
fmt.Println( blob.Size() ) // 16
*/
package jsblob
import (
"github.com/gopherjs/gopherjs/js"
"sync"
)
// Blob wraps a js.Object
type Blob struct {
js.Object
}
type Options struct {
Type string `js:"type"`
Endings string `js:"endings"`
}
// New returns a newly created Blob object whose content consists of the
// concatenation of the array of values given in parameter.
func New(parts []interface{}, opts Options) *Blob {
blob := js.Global.Get("Blob").New(parts, opts)
return &Blob{*blob}
}
// IsClosed returns true if the Close() method (or the underlying JavaScript
// Blobl.close() method) has been called on the blob. Closed blobs can not be
// read.
func (b *Blob) IsClosed() bool {
return b.Get("isClosed").Bool()
}
// Size returns the size, in bytes, of the data contained in the Blob object.
func (b *Blob) Size() int {
return b.Get("size").Int()
}
// Type returns a string indicating the MIME type of the data contained in
// the Blob. If the type is unknown, this string is empty.
func (b *Blob) Type() string {
return b.Get("type").String()
}
// Close closes the blob object, possibly freeing underlying resources.
func (b *Blob) Close() {
b.Call("close")
}
// Slice returns a new Blob object containing the specified range of bytes of the source Blob.
func (b *Blob) Slice(start, end int, contenttype string) *Blob {
newBlob := b.Call("slice", start, end, contenttype)
return &Blob{*newBlob}
}
// Bytes returns a slice of the contents of the Blob.
func (b *Blob) Bytes() []byte {
fileReader := js.Global.Get("FileReader").New()
var wg sync.WaitGroup
var buf []byte
wg.Add(1)
fileReader.Set("onload", js.MakeFunc(func(this *js.Object, _ []*js.Object) interface{} {
defer wg.Done()
buf = js.Global.Get("Uint8Array").New(this.Get("result")).Interface().([]uint8)
return nil
}))
fileReader.Call("readAsArrayBuffer", b)
wg.Wait()
return buf
}