-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblob.go
More file actions
106 lines (97 loc) · 2.17 KB
/
blob.go
File metadata and controls
106 lines (97 loc) · 2.17 KB
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
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
// TmpFiles keeps track of generated files
type tmpFiles struct {
generated map[string]bool
}
// NewTmpFiles create a new tmp struct
func newTmpFiles() *tmpFiles {
return &tmpFiles{
generated: make(map[string]bool),
}
}
func (tmp *tmpFiles) createBinFileLink(content []byte) (string, error) {
var err error
var hostname string
tmpfile, err := ioutil.TempFile("", "thingsdb-cache-")
if err != nil {
return "", err
}
if _, err = tmpfile.Write(content); err != nil {
os.Remove(tmpfile.Name())
return "", err
}
if err = tmpfile.Close(); err != nil {
os.Remove(tmpfile.Name())
return "", err
}
hostname, err = os.Hostname()
if err != nil {
os.Remove(tmpfile.Name())
return "", err
}
tmp.generated[tmpfile.Name()] = true
return fmt.Sprintf("http://%s/download%s", hostname, tmpfile.Name()), nil
}
// ReplaceBinStrWithLink replace a binary string with a symlink
func (tmp *tmpFiles) replaceBinStrWithLink(thing interface{}) (interface{}, error) {
var err error
switch v := thing.(type) {
case []interface{}:
for i := 0; i < len(v); i++ {
if t, ok := v[i].([]byte); ok {
v[i], err = tmp.createBinFileLink(t)
if err != nil {
return nil, err
}
} else {
_, err = tmp.replaceBinStrWithLink(v[i])
if err != nil {
return nil, err
}
}
}
case map[string]interface{}:
for k := range v {
if t, ok := v[k].([]byte); ok {
v[k], err = tmp.createBinFileLink(t)
if err != nil {
return nil, err
}
} else {
_, err = tmp.replaceBinStrWithLink(v[k])
if err != nil {
return nil, err
}
}
}
case []byte:
var s string
s, err = tmp.createBinFileLink(v)
if err != nil {
return nil, err
} else {
return s, nil
}
default:
// no match; here v has the same type as i
}
return nil, nil
}
// CleanupTmp removes downloaded blob files from local tmp folder
func (tmp *tmpFiles) cleanupTmp() error { // cleanup at end of session
var err error
for k := range tmp.generated {
err = os.Remove(k)
delete(tmp.generated, k)
if err != nil && !strings.Contains(err.Error(), "no such file or directory") {
return err
}
}
return nil
}