From 815e624c643ca8ae958713df867c4a2966373ea7 Mon Sep 17 00:00:00 2001 From: cyber-dream Date: Sat, 4 Feb 2023 20:47:42 +0300 Subject: [PATCH] Add osutils files --- osutils/files.go | 3 ++- osutils/json.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 osutils/json.go diff --git a/osutils/files.go b/osutils/files.go index d3e0af7..b366712 100644 --- a/osutils/files.go +++ b/osutils/files.go @@ -56,5 +56,6 @@ func ListDir(path string) ([]fs.FileInfo, error) { func GetParentDir(filePath string) (string, error) { cuttedPath := strings.Split(filePath, "/") cuttedPath = cuttedPath[:len(cuttedPath)-1] - return path.Join(cuttedPath...), nil + finalPath := path.Join("/", path.Join(cuttedPath...)) + return finalPath, nil } diff --git a/osutils/json.go b/osutils/json.go new file mode 100644 index 0000000..522e789 --- /dev/null +++ b/osutils/json.go @@ -0,0 +1,47 @@ +package osutils + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "os" +) + +func WriteStructAsJSON(data interface{}, versionJsonPath string) error { + file, _ := json.MarshalIndent(data, "", " ") + + directory, err := GetParentDir(versionJsonPath) + if err != nil { + return err + } + err = os.MkdirAll(directory+"/", os.ModePerm) + if err != nil { + return err + } + err = ioutil.WriteFile(versionJsonPath, file, 0644) + if err != nil { + return err + } + return nil +} + +func ReadJsonFromDisk(target interface{}, filePath string) error { + // Open our jsonFile + jsonFile, err := os.Open(filePath) + // if we os.Open returns an error then handle it + if err != nil { + fmt.Println(err) + } + + // fmt.Println("Successfully Opened users.json") + // defer the closing of our jsonFile so that we can parse it later on + defer jsonFile.Close() + + // read our opened xmlFile as a byte array. + byteValue, _ := ioutil.ReadAll(jsonFile) + + // we unmarshal our byteArray which contains our + // jsonFile's content into 'users' which we defined above + json.Unmarshal(byteValue, &target) + return nil +}