8683ee7c by fuxiaohei

code style simplify

1 parent 007db805
...@@ -60,12 +60,10 @@ func NewFileCache() *FileCache { ...@@ -60,12 +60,10 @@ func NewFileCache() *FileCache {
60 60
61 // Start and begin gc for file cache. 61 // Start and begin gc for file cache.
62 // the config need to be like {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":2,"EmbedExpiry":0} 62 // the config need to be like {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":2,"EmbedExpiry":0}
63 func (this *FileCache) StartAndGC(config string) error { 63 func (fc *FileCache) StartAndGC(config string) error {
64 64
65 var cfg map[string]string 65 var cfg map[string]string
66 json.Unmarshal([]byte(config), &cfg) 66 json.Unmarshal([]byte(config), &cfg)
67 //fmt.Println(cfg)
68 //fmt.Println(config)
69 if _, ok := cfg["CachePath"]; !ok { 67 if _, ok := cfg["CachePath"]; !ok {
70 cfg["CachePath"] = FileCachePath 68 cfg["CachePath"] = FileCachePath
71 } 69 }
...@@ -78,69 +76,53 @@ func (this *FileCache) StartAndGC(config string) error { ...@@ -78,69 +76,53 @@ func (this *FileCache) StartAndGC(config string) error {
78 if _, ok := cfg["EmbedExpiry"]; !ok { 76 if _, ok := cfg["EmbedExpiry"]; !ok {
79 cfg["EmbedExpiry"] = strconv.FormatInt(FileCacheEmbedExpiry, 10) 77 cfg["EmbedExpiry"] = strconv.FormatInt(FileCacheEmbedExpiry, 10)
80 } 78 }
81 this.CachePath = cfg["CachePath"] 79 fc.CachePath = cfg["CachePath"]
82 this.FileSuffix = cfg["FileSuffix"] 80 fc.FileSuffix = cfg["FileSuffix"]
83 this.DirectoryLevel, _ = strconv.Atoi(cfg["DirectoryLevel"]) 81 fc.DirectoryLevel, _ = strconv.Atoi(cfg["DirectoryLevel"])
84 this.EmbedExpiry, _ = strconv.Atoi(cfg["EmbedExpiry"]) 82 fc.EmbedExpiry, _ = strconv.Atoi(cfg["EmbedExpiry"])
85 83
86 this.Init() 84 fc.Init()
87 return nil 85 return nil
88 } 86 }
89 87
90 // Init will make new dir for file cache if not exist. 88 // Init will make new dir for file cache if not exist.
91 func (this *FileCache) Init() { 89 func (fc *FileCache) Init() {
92 app := filepath.Dir(os.Args[0]) 90 app := filepath.Dir(os.Args[0])
93 this.CachePath = filepath.Join(app, this.CachePath) 91 fc.CachePath = filepath.Join(app, fc.CachePath)
94 ok, err := exists(this.CachePath) 92 if ok, _ := exists(fc.CachePath); !ok { // todo : error handle
95 if err != nil { // print error 93 _ = os.MkdirAll(fc.CachePath, os.ModePerm) // todo : error handle
96 //fmt.Println(err)
97 } 94 }
98 if !ok {
99 if err = os.Mkdir(this.CachePath, os.ModePerm); err != nil {
100 //fmt.Println(err);
101 }
102 }
103 //fmt.Println(this.getCacheFileName("123456"));
104 } 95 }
105 96
106 // get cached file name. it's md5 encoded. 97 // get cached file name. it's md5 encoded.
107 func (this *FileCache) getCacheFileName(key string) string { 98 func (fc *FileCache) getCacheFileName(key string) string {
108 m := md5.New() 99 m := md5.New()
109 io.WriteString(m, key) 100 io.WriteString(m, key)
110 keyMd5 := hex.EncodeToString(m.Sum(nil)) 101 keyMd5 := hex.EncodeToString(m.Sum(nil))
111 cachePath := this.CachePath 102 cachePath := fc.CachePath
112 //fmt.Println("cachepath : " , cachePath) 103 switch fc.DirectoryLevel {
113 //fmt.Println("md5" , keyMd5);
114 switch this.DirectoryLevel {
115 case 2: 104 case 2:
116 cachePath = filepath.Join(cachePath, keyMd5[0:2], keyMd5[2:4]) 105 cachePath = filepath.Join(cachePath, keyMd5[0:2], keyMd5[2:4])
117 case 1: 106 case 1:
118 cachePath = filepath.Join(cachePath, keyMd5[0:2]) 107 cachePath = filepath.Join(cachePath, keyMd5[0:2])
119 } 108 }
120 109
121 ok, err := exists(cachePath) 110 if ok, _ := exists(cachePath); !ok { // todo : error handle
122 if err != nil { 111 _ = os.MkdirAll(cachePath, os.ModePerm) // todo : error handle
123 //fmt.Println(err)
124 } 112 }
125 if !ok { 113
126 if err = os.MkdirAll(cachePath, os.ModePerm); err != nil { 114 return filepath.Join(cachePath, fmt.Sprintf("%s%s", keyMd5, fc.FileSuffix))
127 //fmt.Println(err);
128 }
129 }
130 return filepath.Join(cachePath, fmt.Sprintf("%s%s", keyMd5, this.FileSuffix))
131 } 115 }
132 116
133 // Get value from file cache. 117 // Get value from file cache.
134 // if non-exist or expired, return empty string. 118 // if non-exist or expired, return empty string.
135 func (this *FileCache) Get(key string) interface{} { 119 func (fc *FileCache) Get(key string) interface{} {
136 filename := this.getCacheFileName(key) 120 fileData, err := File_get_contents(fc.getCacheFileName(key))
137 filedata, err := File_get_contents(filename)
138 //fmt.Println("get length:" , len(filedata));
139 if err != nil { 121 if err != nil {
140 return "" 122 return ""
141 } 123 }
142 var to FileCacheItem 124 var to FileCacheItem
143 Gob_decode(filedata, &to) 125 Gob_decode(fileData, &to)
144 if to.Expired < time.Now().Unix() { 126 if to.Expired < time.Now().Unix() {
145 return "" 127 return ""
146 } 128 }
...@@ -150,29 +132,26 @@ func (this *FileCache) Get(key string) interface{} { ...@@ -150,29 +132,26 @@ func (this *FileCache) Get(key string) interface{} {
150 // Put value into file cache. 132 // Put value into file cache.
151 // timeout means how long to keep this file, unit of ms. 133 // timeout means how long to keep this file, unit of ms.
152 // if timeout equals FileCacheEmbedExpiry(default is 0), cache this item forever. 134 // if timeout equals FileCacheEmbedExpiry(default is 0), cache this item forever.
153 func (this *FileCache) Put(key string, val interface{}, timeout int64) error { 135 func (fc *FileCache) Put(key string, val interface{}, timeout int64) error {
154 gob.Register(val) 136 gob.Register(val)
155 137
156 filename := this.getCacheFileName(key) 138 item := FileCacheItem{Data:val}
157 var item FileCacheItem
158 item.Data = val
159 if timeout == FileCacheEmbedExpiry { 139 if timeout == FileCacheEmbedExpiry {
160 item.Expired = time.Now().Unix() + (86400 * 365 * 10) // ten years 140 item.Expired = time.Now().Unix()+(86400*365*10) // ten years
161 } else { 141 } else {
162 item.Expired = time.Now().Unix() + timeout 142 item.Expired = time.Now().Unix()+timeout
163 } 143 }
164 item.Lastaccess = time.Now().Unix() 144 item.Lastaccess = time.Now().Unix()
165 data, err := Gob_encode(item) 145 data, err := Gob_encode(item)
166 if err != nil { 146 if err != nil {
167 return err 147 return err
168 } 148 }
169 err = File_put_contents(filename, data) 149 return File_put_contents(fc.getCacheFileName(key), data)
170 return err
171 } 150 }
172 151
173 // Delete file cache value. 152 // Delete file cache value.
174 func (this *FileCache) Delete(key string) error { 153 func (fc *FileCache) Delete(key string) error {
175 filename := this.getCacheFileName(key) 154 filename := fc.getCacheFileName(key)
176 if ok, _ := exists(filename); ok { 155 if ok, _ := exists(filename); ok {
177 return os.Remove(filename) 156 return os.Remove(filename)
178 } 157 }
...@@ -180,44 +159,41 @@ func (this *FileCache) Delete(key string) error { ...@@ -180,44 +159,41 @@ func (this *FileCache) Delete(key string) error {
180 } 159 }
181 160
182 // Increase cached int value. 161 // Increase cached int value.
183 // this value is saving forever unless Delete. 162 // fc value is saving forever unless Delete.
184 func (this *FileCache) Incr(key string) error { 163 func (fc *FileCache) Incr(key string) error {
185 data := this.Get(key) 164 data := fc.Get(key)
186 var incr int 165 var incr int
187 //fmt.Println(reflect.TypeOf(data).Name())
188 if reflect.TypeOf(data).Name() != "int" { 166 if reflect.TypeOf(data).Name() != "int" {
189 incr = 0 167 incr = 0
190 } else { 168 } else {
191 incr = data.(int) + 1 169 incr = data.(int)+1
192 } 170 }
193 this.Put(key, incr, FileCacheEmbedExpiry) 171 fc.Put(key, incr, FileCacheEmbedExpiry)
194 return nil 172 return nil
195 } 173 }
196 174
197 // Decrease cached int value. 175 // Decrease cached int value.
198 func (this *FileCache) Decr(key string) error { 176 func (fc *FileCache) Decr(key string) error {
199 data := this.Get(key) 177 data := fc.Get(key)
200 var decr int 178 var decr int
201 if reflect.TypeOf(data).Name() != "int" || data.(int)-1 <= 0 { 179 if reflect.TypeOf(data).Name() != "int" || data.(int)-1 <= 0 {
202 decr = 0 180 decr = 0
203 } else { 181 } else {
204 decr = data.(int) - 1 182 decr = data.(int)-1
205 } 183 }
206 this.Put(key, decr, FileCacheEmbedExpiry) 184 fc.Put(key, decr, FileCacheEmbedExpiry)
207 return nil 185 return nil
208 } 186 }
209 187
210 // Check value is exist. 188 // Check value is exist.
211 func (this *FileCache) IsExist(key string) bool { 189 func (fc *FileCache) IsExist(key string) bool {
212 filename := this.getCacheFileName(key) 190 ret, _ := exists(fc.getCacheFileName(key))
213 ret, _ := exists(filename)
214 return ret 191 return ret
215 } 192 }
216 193
217 // Clean cached files. 194 // Clean cached files.
218 // not implemented. 195 // not implemented.
219 func (this *FileCache) ClearAll() error { 196 func (fc *FileCache) ClearAll() error {
220 //this.CachePath
221 return nil 197 return nil
222 } 198 }
223 199
...@@ -235,22 +211,22 @@ func exists(path string) (bool, error) { ...@@ -235,22 +211,22 @@ func exists(path string) (bool, error) {
235 211
236 // Get bytes to file. 212 // Get bytes to file.
237 // if non-exist, create this file. 213 // if non-exist, create this file.
238 func File_get_contents(filename string) ([]byte, error) { 214 func File_get_contents(filename string) (data []byte, e error) {
239 f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, os.ModePerm) 215 f, e := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, os.ModePerm)
240 if err != nil { 216 if e != nil {
241 return []byte(""), err 217 return
242 } 218 }
243 defer f.Close() 219 defer f.Close()
244 stat, err := f.Stat() 220 stat, e := f.Stat()
245 if err != nil { 221 if e != nil {
246 return []byte(""), err 222 return
247 } 223 }
248 data := make([]byte, stat.Size()) 224 data = make([]byte, stat.Size())
249 result, err := f.Read(data) 225 result, e := f.Read(data)
250 if int64(result) == stat.Size() { 226 if e != nil || int64(result) != stat.Size() {
251 return data, err 227 return nil, e
252 } 228 }
253 return []byte(""), err 229 return
254 } 230 }
255 231
256 // Put bytes to file. 232 // Put bytes to file.
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!