github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/filesystem/local/local.go (about)

     1  package local
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/machinefi/w3bstream/pkg/depends/base/consts"
     9  	"github.com/machinefi/w3bstream/pkg/depends/conf/filesystem"
    10  )
    11  
    12  type LocalFileSystem struct {
    13  	Root string `env:""`
    14  }
    15  
    16  func (l *LocalFileSystem) Init() error {
    17  	if l.Root == "" {
    18  		tmp := os.Getenv("TMPDIR")
    19  		if tmp == "" {
    20  			tmp = "/tmp"
    21  		}
    22  		serviceName := os.Getenv(consts.EnvProjectName)
    23  		if serviceName == "" {
    24  			serviceName = "service_tmp"
    25  		}
    26  		l.Root = filepath.Join(tmp, serviceName)
    27  	}
    28  	return os.MkdirAll(filepath.Join(l.Root, os.Getenv(consts.EnvResourceGroup)), 0777)
    29  }
    30  
    31  func (l *LocalFileSystem) SetDefault() {}
    32  
    33  // Upload key full path with filename
    34  func (l *LocalFileSystem) Upload(key string, data []byte) error {
    35  	var (
    36  		fw  io.WriteCloser
    37  		err error
    38  	)
    39  
    40  	path := filepath.Join(l.Root, key)
    41  	if isPathExists(path) {
    42  		return nil
    43  	}
    44  
    45  	if fw, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0666); err != nil {
    46  		return err
    47  	}
    48  	defer fw.Close()
    49  
    50  	if _, err = fw.Write(data); err != nil {
    51  		return err
    52  	}
    53  
    54  	return nil
    55  }
    56  
    57  func (l *LocalFileSystem) Read(key string) ([]byte, error) {
    58  	return os.ReadFile(l.path(key))
    59  }
    60  
    61  func (l *LocalFileSystem) Delete(key string) error {
    62  	return os.Remove(l.path(key))
    63  }
    64  
    65  func (l *LocalFileSystem) StatObject(key string) (*filesystem.ObjectMeta, error) {
    66  	info, err := os.Stat(l.path(key))
    67  	if err != nil {
    68  		return nil, filesystem.ErrNotExistObjectKey
    69  	}
    70  
    71  	om, err := filesystem.ParseObjectMetaFromKey(key)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  	om.Size = info.Size()
    76  
    77  	return om, nil
    78  }
    79  
    80  func (l *LocalFileSystem) path(name string) string {
    81  	return filepath.Join(l.Root, name)
    82  }
    83  
    84  func isPathExists(path string) bool {
    85  	_, err := os.Stat(path)
    86  	return err == nil
    87  }