store/file: add WithDir option (#2038)

This commit is contained in:
ben-toogood
2020-10-07 12:37:28 +01:00
committed by GitHub
parent 27aa1ff2ab
commit c701f96a09
3 changed files with 60 additions and 10 deletions

View File

@@ -13,17 +13,35 @@ import (
)
// NewBlobStore returns a blob file store
func NewBlobStore() (store.BlobStore, error) {
// ensure the parent directory exists
os.MkdirAll(DefaultDir, 0700)
func NewBlobStore(opts ...store.Option) (store.BlobStore, error) {
// parse the options
var options store.Options
for _, o := range opts {
o(&options)
}
return &blobStore{}, nil
var dir string
if options.Context != nil {
if d, ok := options.Context.Value(dirKey{}).(string); ok {
dir = d
}
}
if len(dir) == 0 {
dir = DefaultDir
}
// ensure the parent directory exists
os.MkdirAll(dir, 0700)
return &blobStore{dir}, nil
}
type blobStore struct{}
type blobStore struct {
dir string
}
func (b *blobStore) db() (*bolt.DB, error) {
dbPath := filepath.Join(DefaultDir, "blob.db")
dbPath := filepath.Join(b.dir, "blob.db")
return bolt.Open(dbPath, 0700, &bolt.Options{Timeout: 5 * time.Second})
}

View File

@@ -78,16 +78,32 @@ func (m *fileStore) init(opts ...store.Option) error {
m.options.Table = DefaultTable
}
// create a directory /tmp/micro
dir := filepath.Join(DefaultDir, m.options.Database)
// Ignoring this as the folder might exist.
// Reads/Writes updates will return with sensible error messages
// about the dir not existing in case this cannot create the path anyway
dir := m.getDir(m.options.Database)
os.MkdirAll(dir, 0700)
return nil
}
// getDir returns the directory which should contain the files for a databases
func (m *fileStore) getDir(db string) string {
// get the directory option from the context
var directory string
if m.options.Context != nil {
fd, ok := m.options.Context.Value(dirKey{}).(string)
if ok {
directory = fd
}
}
if len(directory) == 0 {
directory = DefaultDir
}
// construct the directory, e.g. /tmp/micro
return filepath.Join(directory, db)
}
func (f *fileStore) getDB(database, table string) (*bolt.DB, error) {
if len(database) == 0 {
database = f.options.Database
@@ -97,7 +113,7 @@ func (f *fileStore) getDB(database, table string) (*bolt.DB, error) {
}
// create a directory /tmp/micro
dir := filepath.Join(DefaultDir, database)
dir := f.getDir(database)
// create the database handle
fname := table + ".db"
// make the dir

16
store/file/options.go Normal file
View File

@@ -0,0 +1,16 @@
package file
import (
"context"
"github.com/micro/go-micro/v3/store"
)
type dirKey struct{}
// WithDir sets the directory to store the files in
func WithDir(dir string) store.Option {
return func(o *store.Options) {
o.Context = context.WithValue(o.Context, dirKey{}, dir)
}
}