github.com/XiaoMi/Gaea@v1.2.5/models/file/file.go (about) 1 // Copyright 2019 The Gaea Authors. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package file 16 17 import ( 18 "errors" 19 "io/ioutil" 20 "os" 21 "strings" 22 "time" 23 24 "github.com/XiaoMi/Gaea/log" 25 ) 26 27 const ( 28 defaultFilePath = "./etc/file" 29 ) 30 31 // Client used to test with config from file 32 type Client struct { 33 Prefix string 34 } 35 36 // New constructor of EtcdClient 37 func New(path string) (*Client, error) { 38 if strings.TrimSpace(path) == "" { 39 path = defaultFilePath 40 } 41 if err := checkDir(path); err != nil { 42 log.Warn("check file config directory failed, %v", err) 43 return nil, err 44 } 45 return &Client{Prefix: path}, nil 46 } 47 48 func checkDir(path string) error { 49 if strings.TrimSpace(path) == "" { 50 return errors.New("invalid path") 51 } 52 stat, err := os.Stat(path) 53 if err != nil { 54 return err 55 } 56 57 if !stat.IsDir() { 58 return errors.New("invalid path, should be a directory") 59 } 60 61 return nil 62 } 63 64 // Close do nothing 65 func (c *Client) Close() error { 66 return nil 67 } 68 69 // Create do nothing 70 func (c *Client) Create(path string, data []byte) error { 71 return nil 72 } 73 74 // Update do nothing 75 func (c *Client) Update(path string, data []byte) error { 76 return nil 77 } 78 79 // UpdateWithTTL update path with data and ttl 80 func (c *Client) UpdateWithTTL(path string, data []byte, ttl time.Duration) error { 81 return nil 82 } 83 84 // Delete delete path 85 func (c *Client) Delete(path string) error { 86 return nil 87 } 88 89 // Read read file data 90 func (c *Client) Read(file string) ([]byte, error) { 91 value, err := ioutil.ReadFile(file) 92 if err != nil { 93 return nil, err 94 } 95 return value, nil 96 } 97 98 // List list path, return slice of all files 99 func (c *Client) List(path string) ([]string, error) { 100 r := make([]string, 0) 101 files, err := ioutil.ReadDir(path) 102 if err != nil { 103 return r, err 104 } 105 106 for _, f := range files { 107 r = append(r, f.Name()) 108 } 109 110 return r, nil 111 } 112 113 // BasePrefix return base prefix 114 func (c *Client) BasePrefix() string { 115 return c.Prefix 116 }