Skip to content

Commit

Permalink
Support unmarshal custom type (#127)
Browse files Browse the repository at this point in the history
  • Loading branch information
XIELongDragon committed Jul 19, 2022
1 parent 2999b2a commit 7766e43
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
23 changes: 23 additions & 0 deletions aconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package aconfig

import (
"embed"
"fmt"
"io/ioutil"
"net/url"
"os"
Expand All @@ -11,6 +12,25 @@ import (
"time"
)

type LogLevel int8

func (l *LogLevel) UnmarshalText(text []byte) error {
switch string(text) {
case "debug":
*l = -1
case "info":
*l = 0
case "warn":
*l = 1
case "error":
*l = 2
default:
return fmt.Errorf("unknown log level: %s", text)
}

return nil
}

func TestDefaults(t *testing.T) {
var cfg TestConfig
loader := LoaderFor(&cfg, Config{
Expand Down Expand Up @@ -71,6 +91,8 @@ func TestDefaults_AllTypes(t *testing.T) {

Dur time.Duration `default:"1h2m3s"`
Time time.Time `default:"2000-04-05 10:20:30 +0000 UTC"`

Level LogLevel `default:"warn"`
}

var cfg AllTypesConfig
Expand Down Expand Up @@ -101,6 +123,7 @@ func TestDefaults_AllTypes(t *testing.T) {
Dur: time.Hour + 2*time.Minute + 3*time.Second,
// TODO
// Time :2000-04-05 10:20:30 +0000 UTC,
Level: LogLevel(1),
}

if got := cfg; got != want {
Expand Down
6 changes: 6 additions & 0 deletions reflection.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package aconfig

import (
"encoding"
"fmt"
"reflect"
"strconv"
Expand Down Expand Up @@ -158,6 +159,11 @@ func (l *Loader) setFieldData(field *fieldData, value interface{}) error {
return nil
}

pv := field.value.Addr().Interface()
if v, ok := pv.(encoding.TextUnmarshaler); ok {
return v.UnmarshalText([]byte(fmt.Sprint(value)))
}

switch kind := field.value.Type().Kind(); kind {
case reflect.Bool:
return l.setBool(field, fmt.Sprint(value))
Expand Down

0 comments on commit 7766e43

Please sign in to comment.