-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwriter.go
More file actions
42 lines (35 loc) · 838 Bytes
/
writer.go
File metadata and controls
42 lines (35 loc) · 838 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package netconfigparser
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
func WriteConfigStructToJSON(data any, outFileName string) error {
// Create the "out" directory if it doesn't exist
outDir := "out"
err := os.MkdirAll(outDir, os.ModePerm)
if err != nil {
return fmt.Errorf("error creating directory: %v", err)
}
// Ensure outFileName is within the "out" directory
if !filepath.HasPrefix(outFileName, outDir) {
outFileName = filepath.Join(outDir, outFileName)
}
jsonData, err := json.MarshalIndent(data, "", " ")
if err != nil {
return err
}
// Create a file to save the JSON data
jsonFile, err := os.Create(outFileName)
if err != nil {
return err
}
defer jsonFile.Close()
// Write the JSON data to the file
_, err = jsonFile.Write(jsonData)
if err != nil {
return err
}
return nil
}