-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parsers.go
243 lines (219 loc) · 6.81 KB
/
parsers.go
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package gosl
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/knadh/koanf/parsers/hcl"
"github.com/knadh/koanf/parsers/json"
"github.com/knadh/koanf/parsers/toml"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/env"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/providers/rawbytes"
"github.com/knadh/koanf/v2"
)
// ParseFileToStruct parses the given file from path to struct *T using
// "knadh/koanf" package.
//
// You can use any of the supported file formats (JSON, YAML, TOML, or HCL). The
// structured file can be placed both locally (by system path) and accessible via
// HTTP (by URL).
//
// If err != nil, returns zero-value for a struct and error.
//
// Example:
//
// package main
//
// import (
// "fmt"
// "log"
//
// "github.com/koddr/gosl"
// )
//
// type server struct {
// Host string `koanf:"host"`
// Port string `koanf:"port"`
// }
//
// func main() {
// pathToFile := "path/to/server.json"
// structToParse := &server{}
//
// srv, err := gosl.ParseFileToStruct(pathToFile, structToParse)
// if err != nil {
// log.Fatal(err)
// }
//
// fmt.Println(srv)
// }
func ParseFileToStruct[T any](path string, model *T) (*T, error) {
// Check, if path is not empty.
if path == "" {
return nil, errors.New("error: given path of the structured file is empty")
}
// Create a new koanf instance and parse the given path.
k, err := newKoanfByPath(path)
if err != nil {
return nil, err
}
// Unmarshal structured data to the given struct.
if err = k.Unmarshal("", &model); err != nil {
return nil, fmt.Errorf("error unmarshalling data from structured file to struct, %w", err)
}
return model, nil
}
// ParseFileWithEnvToStruct parses the given file from path to struct *T using
// "knadh/koanf" package with an (optional) environment variables for a secret
// data.
//
// You can use any of the supported file formats (JSON, YAML, TOML, or HCL). The
// structured file can be placed both locally (by system path) and accessible via
// HTTP (by URL).
//
// If err != nil, returns zero-value for a struct and error.
//
// Example:
//
// package main
//
// import (
// "fmt"
// "log"
//
// "github.com/koddr/gosl"
// )
//
// type config struct {
// ServerURL string `koanf:"server_url"`
// AuthType string `koanf:"auth_type"`
// Token string `koanf:"token"`
// }
//
// func main() {
// pathToFile := "https://github.com/user/repo/config.yaml"
// envPrefix := "MY_CONFIG" // for ex., MY_CONFIG_TOKEN=my-secret-1234567
// structToParse := &config{}
//
// cfg, err := gosl.ParseFileWithEnvToStruct(pathToFile, envPrefix, structToParse)
// if err != nil {
// log.Fatal(err)
// }
//
// fmt.Println(cfg)
// }
func ParseFileWithEnvToStruct[T any](path, envPrefix string, model *T) (*T, error) {
// Check, if path is not empty.
if path == "" {
return nil, errors.New("error: given path of the structured file is empty")
}
// Check, if environment variables prefix was given.
if envPrefix == "" {
return nil, errors.New("error: given environment variables prefix is empty")
}
// Create a new koanf instance and parse the given path.
k, err := newKoanfByPath(path)
if err != nil {
return nil, err
}
// Load environment variables.
if err = k.Load(env.Provider(envPrefix, ".", func(s string) string {
// Return cleared value of the environment variables.
return strings.ReplaceAll(
strings.ToLower(strings.TrimPrefix(s, fmt.Sprintf("%s_", envPrefix))),
"_", ".",
)
}), nil); err != nil {
return nil, fmt.Errorf("error parsing environment variables, %w", err)
}
// Merge environment variables into the structured file data.
if err = k.Merge(k); err != nil {
return nil, fmt.Errorf("error merging environment variables into the structured file data, %w", err)
}
// Unmarshal structured data to the given struct.
if err = k.Unmarshal("", &model); err != nil {
return nil, fmt.Errorf("error unmarshalling data from structured file to struct, %w", err)
}
return model, nil
}
// newKoanfByPath helps to parse the given path for ParseFileToStruct and
// ParseFileWithEnvToStruct functions.
func newKoanfByPath(path string) (*koanf.Koanf, error) {
// Create a new koanf instance.
k := koanf.New(".")
// Create a new variable with structured file extension.
parserFormat := filepath.Ext(path)
// Check the format of the structured file.
switch parserFormat {
case ".json", ".yaml", ".yml", ".toml", ".tf":
// Create a new variable for the koanf parser.
var parser koanf.Parser
// Check the format of the structured file for get right koanf parser.
switch parserFormat {
case ".json":
parser = json.Parser() // JSON format parser
case ".yaml", ".yml":
parser = yaml.Parser() // YAML format parser
case ".toml":
parser = toml.Parser() // TOML format parser
case ".tf":
parser = hcl.Parser(true) // HCL (Terraform) format parser
}
// Parse path of the structured file as URL.
u, _ := url.Parse(path)
// Check the schema of the given URL.
switch u.Scheme {
case "", "file":
// Get the structured file from system path.
fileInfo, err := os.Stat(path)
// Check, if file exists.
if err == nil || !os.IsNotExist(err) {
// Check, if file is not dir.
if fileInfo.IsDir() {
return nil, fmt.Errorf("error: path of the structured file (%s) is dir", path)
}
// Load structured file from path (with parser of the file format).
if err = k.Load(file.Provider(path), parser); err != nil {
return nil, fmt.Errorf(
"error: not valid structure of the %s file from the given path (%s)",
strings.ToUpper(strings.TrimPrefix(parserFormat, ".")), path,
)
}
} else {
return nil, fmt.Errorf("error: structured file is not found in the given path (%s)", path)
}
case "http", "https":
// Get the given file from URL.
resp, err := http.Get(path)
if err != nil {
return nil, fmt.Errorf("error: structured file is not found in the given URL (%s)", path)
}
defer resp.Body.Close()
// Read the structured file from URL.
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.New("error: raw body from the URL is not valid")
}
// Load structured file from URL (with parser of the file format).
if err = k.Load(rawbytes.Provider(body), parser); err != nil {
return nil, fmt.Errorf(
"error: not valid structure of the %s file from the given URL (%s)",
strings.ToUpper(strings.TrimPrefix(parserFormat, ".")), path,
)
}
default:
// If the path's schema is unknown, default action is error.
return nil, errors.New("error: unknown path of structured file, use system path or http(s) URL")
}
default:
// If the format of the structured file is unknown, default action is error.
return nil, errors.New("error: unknown format of structured file, see: https://github.com/knadh/koanf")
}
return k, nil
}