github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/storage/storage_operations_local_fs.go (about) 1 package storage 2 3 import ( 4 "io" 5 "os" 6 "path/filepath" 7 8 "github.com/machinefi/w3bstream/pkg/depends/base/consts" 9 ) 10 11 type LocalFs struct { 12 Root string `env:""` 13 } 14 15 func (l *LocalFs) Init() error { 16 if l.Root == "" { 17 tmp := os.Getenv("TMPDIR") 18 if tmp == "" { 19 tmp = "/tmp" 20 } 21 serviceName := os.Getenv(consts.EnvProjectName) 22 if serviceName == "" { 23 serviceName = "service_tmp" 24 } 25 l.Root = filepath.Join(tmp, serviceName) 26 } 27 return os.MkdirAll(filepath.Join(l.Root, os.Getenv(consts.EnvResourceGroup)), 0777) 28 } 29 30 func (l *LocalFs) Type() StorageType { return STORAGE_TYPE__FILESYSTEM } 31 32 func (l *LocalFs) SetDefault() {} 33 34 // Upload key full path with filename 35 func (l *LocalFs) Upload(key string, data []byte, chk ...HmacAlgType) error { 36 var ( 37 fw io.WriteCloser 38 err error 39 ) 40 41 path := filepath.Join(l.Root, key) 42 if IsPathExists(path) { 43 return nil 44 } 45 46 if fw, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0666); err != nil { 47 return err 48 } 49 defer fw.Close() 50 51 if _, err = fw.Write(data); err != nil { 52 return err 53 } 54 55 return nil 56 } 57 58 func (l *LocalFs) Read(key string, chk ...HmacAlgType) (data []byte, sum []byte, err error) { 59 data, err = os.ReadFile(filepath.Join(l.Root, key)) 60 if err != nil { 61 return 62 } 63 t := HMAC_ALG_TYPE__MD5 64 if len(chk) > 0 && chk[0] != 0 { 65 t = chk[0] 66 } 67 sum = t.Sum(data) 68 return 69 } 70 71 func (l *LocalFs) Delete(key string) error { 72 return os.Remove(filepath.Join(l.Root, key)) 73 } 74 75 func IsPathExists(path string) bool { 76 _, err := os.Stat(path) 77 return err == nil 78 }