File: json_parser.go

package info (click to toggle)
golang-github-peterbourgon-ff 3.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 408 kB
  • sloc: sh: 9; makefile: 4
file content (60 lines) | stat: -rw-r--r-- 1,587 bytes parent folder | download
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
package ff

import (
	"encoding/json"
	"fmt"
	"io"

	"github.com/peterbourgon/ff/v3/internal"
)

// JSONParser is a helper function that uses a default JSONParseConfig.
func JSONParser(r io.Reader, set func(name, value string) error) error {
	return (&JSONParseConfig{}).Parse(r, set)
}

// JSONParseConfig collects parameters for the JSON config file parser.
type JSONParseConfig struct {
	// Delimiter is used when concatenating nested node keys into a flag name.
	// The default delimiter is ".".
	Delimiter string
}

// Parse a JSON document from the provided io.Reader, using the provided set
// function to set flag values. Flag names are derived from the node names and
// their key/value pairs.
func (pc *JSONParseConfig) Parse(r io.Reader, set func(name, value string) error) error {
	if pc.Delimiter == "" {
		pc.Delimiter = "."
	}

	d := json.NewDecoder(r)
	d.UseNumber() // required for stringifying values

	var m map[string]interface{}
	if err := d.Decode(&m); err != nil {
		return JSONParseError{Inner: err}
	}

	if err := internal.TraverseMap(m, pc.Delimiter, set); err != nil {
		return JSONParseError{Inner: err}
	}

	return nil
}

// JSONParseError wraps all errors originating from the JSONParser.
type JSONParseError struct {
	Inner error
}

// Error implenents the error interface.
func (e JSONParseError) Error() string {
	return fmt.Sprintf("error parsing JSON config: %v", e.Inner)
}

// Unwrap implements the errors.Wrapper interface, allowing errors.Is and
// errors.As to work with JSONParseErrors.
func (e JSONParseError) Unwrap() error {
	return e.Inner
}