Add osutils files

This commit is contained in:
cyber-dream 2023-02-04 20:47:42 +03:00
parent 6f1cc3cc7c
commit 815e624c64
2 changed files with 49 additions and 1 deletions

View File

@ -56,5 +56,6 @@ func ListDir(path string) ([]fs.FileInfo, error) {
func GetParentDir(filePath string) (string, error) { func GetParentDir(filePath string) (string, error) {
cuttedPath := strings.Split(filePath, "/") cuttedPath := strings.Split(filePath, "/")
cuttedPath = cuttedPath[:len(cuttedPath)-1] cuttedPath = cuttedPath[:len(cuttedPath)-1]
return path.Join(cuttedPath...), nil finalPath := path.Join("/", path.Join(cuttedPath...))
return finalPath, nil
} }

47
osutils/json.go Normal file
View File

@ -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
}