Created
April 16, 2023 00:51
-
-
Save lukaszraczylo/c9f0d7fb310bcd0ce441f609497f0a49 to your computer and use it in GitHub Desktop.
Convert json value into desired type using Golang generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Function: | |
func ConvertReplyType[T any](desiredType T, reply *[]byte) T { | |
if reply == nil { | |
return interface{}(nil).(T) | |
} | |
// reflect type of desired type | |
desiredTypeType := reflect.TypeOf(desiredType) | |
v := reflect.New(desiredTypeType).Interface() | |
// try to convert reply to desired type | |
err := json.Unmarshal(*reply, &v) | |
if err != nil { | |
log.Critical("Can't convert reply to desired type", map[string]interface{}{"error": err.Error()}) | |
return interface{}(nil).(T) | |
} | |
return reflect.ValueOf(v).Elem().Interface().(T) | |
} | |
// Tests | |
func (suite *NatsTestSuite) TestConvertReplyType() { | |
type args struct { | |
desired_reply_type interface{} | |
reply []byte | |
} | |
tests := []struct { | |
name string | |
args args | |
want interface{} | |
}{ | |
{ | |
name: "TestConvertReplyType - slice of int", | |
args: args{ | |
desired_reply_type: []int{}, | |
reply: []byte("[1,2,3]"), | |
}, | |
want: []int{1, 2, 3}, | |
}, | |
{ | |
name: "TestConvertReplyType - struct", | |
args: args{ | |
desired_reply_type: struct { | |
Name string | |
Age int | |
}{}, | |
reply: []byte("{\"Name\":\"test\",\"Age\":10}"), | |
}, | |
want: struct { | |
Name string | |
Age int | |
}{ | |
Name: "test", | |
Age: 10, | |
}, | |
}, | |
{ | |
name: "TestConvertReplyType - string", | |
args: args{ | |
desired_reply_type: "", | |
reply: []byte("\"test\""), | |
}, | |
want: "test", | |
}, | |
{ | |
name: "TestConvertReplyType - []float64", | |
args: args{ | |
desired_reply_type: []float64{}, | |
reply: []byte("[1.1,2.2,3.3]"), | |
}, | |
want: []float64{1.1, 2.2, 3.3}, | |
}, | |
} | |
for _, tt := range tests { | |
suite.T().Run(tt.name, func(t *testing.T) { | |
got := ConvertReplyType(tt.args.desired_reply_type, &tt.args.reply) | |
assert.Equal(t, tt.want, got) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment