feat: add toml config (#1899)
This commit is contained in:
29
core/mapping/tomlunmarshaler.go
Normal file
29
core/mapping/tomlunmarshaler.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package mapping
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
)
|
||||
|
||||
// UnmarshalTomlBytes unmarshals TOML bytes into the given v.
|
||||
func UnmarshalTomlBytes(content []byte, v interface{}) error {
|
||||
return UnmarshalTomlReader(bytes.NewReader(content), v)
|
||||
}
|
||||
|
||||
// UnmarshalTomlReader unmarshals TOML from the given io.Reader into the given v.
|
||||
func UnmarshalTomlReader(r io.Reader, v interface{}) error {
|
||||
var val interface{}
|
||||
if err := toml.NewDecoder(r).Decode(&val); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := json.NewEncoder(&buf).Encode(val); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return UnmarshalJsonReader(&buf, v)
|
||||
}
|
||||
41
core/mapping/tomlunmarshaler_test.go
Normal file
41
core/mapping/tomlunmarshaler_test.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package mapping
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestUnmarshalToml(t *testing.T) {
|
||||
const input = `a = "foo"
|
||||
b = 1
|
||||
c = "${FOO}"
|
||||
d = "abcd!@#$112"
|
||||
`
|
||||
var val struct {
|
||||
A string `json:"a"`
|
||||
B int `json:"b"`
|
||||
C string `json:"c"`
|
||||
D string `json:"d"`
|
||||
}
|
||||
assert.Nil(t, UnmarshalTomlBytes([]byte(input), &val))
|
||||
assert.Equal(t, "foo", val.A)
|
||||
assert.Equal(t, 1, val.B)
|
||||
assert.Equal(t, "${FOO}", val.C)
|
||||
assert.Equal(t, "abcd!@#$112", val.D)
|
||||
}
|
||||
|
||||
func TestUnmarshalTomlErrorToml(t *testing.T) {
|
||||
const input = `foo"
|
||||
b = 1
|
||||
c = "${FOO}"
|
||||
d = "abcd!@#$112"
|
||||
`
|
||||
var val struct {
|
||||
A string `json:"a"`
|
||||
B int `json:"b"`
|
||||
C string `json:"c"`
|
||||
D string `json:"d"`
|
||||
}
|
||||
assert.NotNil(t, UnmarshalTomlBytes([]byte(input), &val))
|
||||
}
|
||||
Reference in New Issue
Block a user