OSDN Git Service

upload (#576)
[bytom/vapor.git] / toolbar / osssync / util / json.go
1 package util
2
3 import (
4         "encoding/json"
5         "io/ioutil"
6         "os"
7 )
8
9 // NewFileUtil creates new file util
10 func NewFileUtil(localDir string) *FileUtil {
11         return &FileUtil{localDir}
12 }
13
14 // SaveBlockFile saves block file
15 func (f *FileUtil) SaveBlockFile(filename string, data interface{}) (bool, error) {
16         filename = f.LocalDir + "/" + filename + ".json"
17         saveData, err := json.Marshal(data)
18         if err != nil {
19                 return false, err
20         }
21
22         err = ioutil.WriteFile(filename, saveData, 0644)
23         if err != nil {
24                 return false, err
25         }
26
27         return true, nil
28 }
29
30 // GetJson read json file
31 func (f *FileUtil) GetJson(filename string) (json.RawMessage, error) {
32         filename = f.LocalDir + "/" + filename + ".json"
33         return ioutil.ReadFile(filename)
34 }
35
36 // RemoveLocal deletes file
37 func (f *FileUtil) RemoveLocal(filename string) error {
38         return os.Remove(f.LocalDir + "/" + filename)
39 }
40
41 // Json2Struct transform json to struct
42 func Json2Struct(data json.RawMessage, resp interface{}) error {
43         return json.Unmarshal(data, &resp)
44 }
45
46 // Struct2Json transform struct to json
47 func Struct2Json(theStruct interface{}) (json.RawMessage, error) {
48         return json.Marshal(theStruct)
49 }