/
storage_local.go
84 lines (69 loc) · 1.68 KB
/
storage_local.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
/*
Copyright (C) 2013 Aaron Lindsay <aaron@aclindsay.com>
*/
package main
import (
"code.google.com/p/goconf/conf"
"errors"
"github.com/aclindsa/asink/util"
"io"
"io/ioutil"
"os"
"path"
)
type LocalStorage struct {
storageDir string
tmpSubdir string
}
func NewLocalStorage(config *conf.ConfigFile) (*LocalStorage, error) {
storageDir, err := config.GetString("storage", "dir")
if err != nil {
return nil, errors.New("Error: LocalStorage indicated in config file, but lacking local storage directory ('dir = some/dir').")
}
ls := new(LocalStorage)
ls.storageDir = storageDir
ls.tmpSubdir = path.Join(storageDir, ".asink-tmpdir")
//make sure the base directory and tmp subdir exist
err = util.EnsureDirExists(ls.storageDir)
if err != nil {
return nil, err
}
err = util.EnsureDirExists(ls.tmpSubdir)
if err != nil {
return nil, err
}
return ls, nil
}
type putWriteCloser struct {
outfile *os.File
filename string
done chan error
}
func (wc putWriteCloser) Write(p []byte) (n int, err error) {
return wc.outfile.Write(p)
}
func (wc putWriteCloser) Close() error {
tmpfilename := wc.outfile.Name()
wc.outfile.Close()
err := os.Rename(tmpfilename, wc.filename)
if err != nil {
os.Remove(tmpfilename)
}
wc.done <- err
return err
}
func (ls *LocalStorage) Put(hash string, done chan error) (w io.WriteCloser, e error) {
outfile, err := ioutil.TempFile(ls.tmpSubdir, "asink")
if err != nil {
return nil, err
}
w = putWriteCloser{outfile, path.Join(ls.storageDir, hash), done}
return
}
func (ls *LocalStorage) Get(hash string) (r io.ReadCloser, e error) {
r, err := os.Open(path.Join(ls.storageDir, hash))
if err != nil {
return nil, err
}
return
}