|
| 1 | +package data_store |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "go.uber.org/zap" |
| 6 | + "io" |
| 7 | + "io/ioutil" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +type LocalClient struct { |
| 13 | + DataPath string |
| 14 | +} |
| 15 | + |
| 16 | +func newLocalClient(config DataStoreConfig) (LocalClient, error) { |
| 17 | + return LocalClient{DataPath: config.DataPath}, nil |
| 18 | +} |
| 19 | + |
| 20 | +func (c LocalClient) GetFile(object string, bucket string) (*[]byte, error) { |
| 21 | + targetObject := fmt.Sprintf("%s/%s/%s", c.DataPath, bucket, object) |
| 22 | + data, err := ioutil.ReadFile(targetObject) |
| 23 | + if err != nil { |
| 24 | + zap.S().Errorf("err when getting object from store: %v", err.Error()) |
| 25 | + return nil, err |
| 26 | + } |
| 27 | + |
| 28 | + return &data, nil |
| 29 | +} |
| 30 | + |
| 31 | +func (c LocalClient) List(bucket string, prefix string) *[]string { |
| 32 | + var list []string |
| 33 | + files, err := os.ReadDir(fmt.Sprintf("%s/%s", c.DataPath, bucket)) |
| 34 | + if err != nil { |
| 35 | + zap.S().Errorf("could not read directory '%s': %v", bucket, err) |
| 36 | + return &list |
| 37 | + } |
| 38 | + |
| 39 | + for _, file := range files { |
| 40 | + fileName := file.Name() |
| 41 | + if strings.Contains(fileName, prefix) { |
| 42 | + list = append(list, fileName) |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return &list |
| 47 | +} |
| 48 | + |
| 49 | +func (c LocalClient) UploadFile(name string, dest string) error { |
| 50 | + file, err := os.Open(name) |
| 51 | + if err != nil { |
| 52 | + return err |
| 53 | + } |
| 54 | + defer file.Close() |
| 55 | + |
| 56 | + fileStat, err := file.Stat() |
| 57 | + if err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + |
| 61 | + if !fileStat.Mode().IsRegular() { |
| 62 | + return fmt.Errorf("%s is not a regular file", name) |
| 63 | + } |
| 64 | + |
| 65 | + out, err := os.Create(fmt.Sprintf("%s/%s/%s", c.DataPath, dest, name)) |
| 66 | + if err != nil { |
| 67 | + return err |
| 68 | + } |
| 69 | + defer out.Close() |
| 70 | + |
| 71 | + _, err = io.Copy(out, file) |
| 72 | + return err |
| 73 | +} |
| 74 | + |
| 75 | +func (c LocalClient) StorageType() string { |
| 76 | + return LocalStorage |
| 77 | +} |
0 commit comments