-
Notifications
You must be signed in to change notification settings - Fork 1
/
storage.go
64 lines (52 loc) · 1.12 KB
/
storage.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
package main
import (
"io"
"math/rand"
"os"
"path/filepath"
"time"
)
const CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
const ID_LENGTH = 6
func init() {
rand.Seed(time.Now().UnixNano())
}
type Storage struct {
root string
}
func NewStorage(root string) *Storage {
return &Storage{root}
}
func (s *Storage) Create() (id string, dest io.WriteCloser, err error) {
// create id
var idbytes = make([]byte, ID_LENGTH)
for idx := 0; idx < ID_LENGTH; idx++ {
idbytes[idx] = CHARS[rand.Intn(len(CHARS))]
}
id = string(idbytes)
// create file storage
path := s.GetPath(id)
baseDir := filepath.Dir(path)
if _, err = os.Stat(baseDir); os.IsNotExist(err) {
err = os.MkdirAll(baseDir, 0777)
if err != nil {
return "", nil, err
}
}
file, err := os.Create(path)
if err != nil {
return "", nil, err
}
return id, file, nil
}
func (s *Storage) Open(id string) (io.ReadCloser, error) {
path := s.GetPath(id)
file, err := os.Open(path)
if err != nil {
return nil, err
}
return file, nil
}
func (s *Storage) GetPath(id string) string {
return filepath.Join(s.root, id[:2]+"/"+id[2:])
}