mercredi 24 octobre 2018

In Golang, Is it possible to dynamically set the output of json.Unmarshal?

I have the following Go code:

var typeRegistry = make(map[string]reflect.Type)

func init() {
    typeRegistry["User"] = reflect.TypeOf(User{})
}

func makeInstance(name string) interface{} {
    v := reflect.New(typeRegistry[name]).Elem()
    return v.Interface()
}

func Invoke(any interface{}, name string, body []byte, signature Signature) {
    args := signature.Args
    data := makeInstance(signature.Args[0])
    json.Unmarshal(body, &data)
    inputs := make([]reflect.Value, len(args))
    for i, _ := range signature.Args {
        log.Println(reflect.TypeOf(data))
        log.Println(reflect.ValueOf(data))
        inputs[i] = reflect.ValueOf(data)
    }
    reflect.ValueOf(any).MethodByName(name).Call(inputs)
}

I'm attempting to pass in some JSON, and a string denoting what type the JSON should be mapped to. I'm attempting to use reflection to mush the two together again and pass it into a method by the methods name.

I kind of got it working, however, when I use a pointer un json.Unmarshal it seems to lose the reference to its assigned type again, and defaults back to map[string]interface{} which is a mis-match for the method I'm calling. In this case it's expecting type main.User. If I remove the pointer from json.Unmarshal(body, data) the types match correctly, but obviously the data is no longer being set for data.

I'm aware I'm bastardising Go's type-system, and probably using the language in ways that isn't suggested, but I'm trying to do something more academic than useful, I guess.





Aucun commentaire:

Enregistrer un commentaire