Support the "mapstructure:" tag on structs for custom keys
diff --git a/mapstructure.go b/mapstructure.go
index 53d632f..344bb7f 100644
--- a/mapstructure.go
+++ b/mapstructure.go
@@ -210,6 +210,11 @@
fieldType := valType.Field(i)
fieldName := fieldType.Name
+ tagValue := fieldType.Tag.Get("mapstructure")
+ if tagValue != "" {
+ fieldName = tagValue
+ }
+
rawMapVal := dataVal.MapIndex(reflect.ValueOf(fieldName))
if !rawMapVal.IsValid() {
// Do a slower search by iterating over each key and
diff --git a/mapstructure_test.go b/mapstructure_test.go
index f131397..663f520 100644
--- a/mapstructure_test.go
+++ b/mapstructure_test.go
@@ -33,6 +33,10 @@
Value []Basic
}
+type Tagged struct {
+ Value string `mapstructure:"foo"`
+}
+
func TestBasicTypes(t *testing.T) {
t.Parallel()
@@ -318,7 +322,7 @@
}
}
-func TestNontStructValue(t *testing.T) {
+func TestNonStructValue(t *testing.T) {
t.Parallel()
result := 42
@@ -333,6 +337,25 @@
}
}
+func TestTagged(t *testing.T) {
+ t.Parallel()
+
+ input := map[string]interface{}{
+ "foo": "bar",
+ }
+
+ var result Tagged
+ err := Decode(input, &result)
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ t.FailNow()
+ }
+
+ if result.Value != "bar" {
+ t.Errorf("value should be 'bar', got: %#v", result.Value)
+ }
+}
+
func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) {
var result Slice
err := Decode(input, &result)