go-asink/asink/storage_local.go

86 lines
1.6 KiB
Go
Raw Normal View History

2013-09-04 22:02:17 -04:00
/*
Copyright (C) 2013 Aaron Lindsay <aaron@aclindsay.com>
*/
2013-02-10 23:39:23 -05:00
package main
import (
"asink/util"
2013-02-11 23:17:12 -05:00
"code.google.com/p/goconf/conf"
"errors"
2013-02-10 23:39:23 -05:00
"io"
"io/ioutil"
2013-02-11 23:17:12 -05:00
"os"
2013-02-10 23:39:23 -05:00
"path"
)
type LocalStorage struct {
storageDir string
2013-02-11 23:17:12 -05:00
tmpSubdir string
2013-02-10 23:39:23 -05:00
}
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)
2013-02-11 23:17:12 -05:00
if err != nil {
return nil, err
}
err = util.EnsureDirExists(ls.tmpSubdir)
2013-02-11 23:17:12 -05:00
if err != nil {
return nil, err
}
2013-02-10 23:39:23 -05:00
return ls, nil
}
type putWriteCloser struct {
outfile *os.File
filename string
}
2013-02-10 23:39:23 -05:00
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 {
err := os.Remove(tmpfilename)
2013-02-11 23:17:12 -05:00
if err != nil {
return err
}
}
2013-02-10 23:39:23 -05:00
return nil
}
func (ls *LocalStorage) Put(hash string) (w io.WriteCloser, e error) {
outfile, err := ioutil.TempFile(ls.tmpSubdir, "asink")
2013-02-11 23:17:12 -05:00
if err != nil {
return nil, err
2013-02-11 23:17:12 -05:00
}
2013-02-10 23:39:23 -05:00
w = putWriteCloser{outfile, path.Join(ls.storageDir, hash)}
2013-02-10 23:39:23 -05:00
return
}
2013-02-10 23:39:23 -05:00
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
2013-02-10 23:39:23 -05:00
}