diff --git a/store/file/blob.go b/store/file/blob.go index 4c7a0e52..5cb28c5b 100644 --- a/store/file/blob.go +++ b/store/file/blob.go @@ -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}) } diff --git a/store/file/file.go b/store/file/file.go index 5a963156..0c4089a5 100644 --- a/store/file/file.go +++ b/store/file/file.go @@ -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 diff --git a/store/file/options.go b/store/file/options.go new file mode 100644 index 00000000..a00b2981 --- /dev/null +++ b/store/file/options.go @@ -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) + } +}