This is a creation in Article, where the information may have evolved or changed.
-
- Cause
- Get the method specified by the struct by reflection
- Called through a JSON string
- Proper perfection.
Cause
On many occasions there is a need or idea: to submit a JSON like this
{ "func_name":"FooBarAdd", "params":[ 123.4, 432.1 ]}
And then get a JSON like this
{ "func_name":"FooBarAdd", "data":[ 555.5 ]}
To achieve this, it is necessary to parse the submitted JSON, get the method name and parameters, then find the entity that owns the method, convert the arguments to the appropriate type, call the method, and finally wrap the resulting results in JSON return.
As to whether this JSON is submitted and returned through HTTP, or through WebSocket commit and return, or through TCP direct commit and return, it is possible. Let's take a look at how to achieve this.
Get the method specified by the struct by reflection
Suppose there's a struct like this now.
typestruct {}funcfloat64float64 { return argOne + argTwo}
For the Barfuncadd method, you can call this:
foobar := &FooBar{}resultCallByName :=reflect.ValueOf(foobar).MethodByName("FooBarAdd"). Call([]reflect.Value{reflect.ValueOf(123.4),reflect.ValueOf(432.1)})fmt.Println(resultCallByName[0].Float())
You can also call this:
foobar := &FooBar{}resultCallByIndex :=reflect.ValueOf(foobar).Method(0). Call([]reflect.Value{reflect.ValueOf(123.4),reflect.ValueOf(432.1)})fmt.Println(resultCallByIndex[0].Float())
The results are all 555.5.
Called through a JSON string
If you want to use a bunch of these JSON
{ "func_name":"FooBarAdd", "params":[ 123.4, 432.1 ]}
To get a result like this
{ "func_name":"FooBarAdd", "data":[ 555.5 ]}
You can call this
Foobar: = &foobar{}jsondata: =' {' func_name ': ' Foobaradd ', ' params ': [12 3.4, 432.1]} 'typeRequestinfostruct{FuncNamestring ' JSON: ' Func_name 'Params []Interface{}' JSON: ' params '}typeResultinfostruct{FuncNamestring ' JSON: ' Func_name 'Data []Interface{}' JSON: ' Data '}requestinfo: = &requestinfo{}json. Unmarshal ([]byte(Jsondata), &requestinfo) Resultcallbyjson: =reflect. ValueOf (Foobar). Methodbyname (Requestinfo.funcname). Call ([]reflect. Value{reflect. ValueOf (requestinfo.params[0]), reflect. ValueOf (requestinfo.params[1]) Result: = &resultinfo{funcname:requestinfo.funcname, Data: []Interface{{Resultcallbyjson[0]. Interface ()}}jsonresult, _: = json. Marshal (&result) fmt. Printf ("%s\n", Jsonresult)
Proper perfection.
Do you think there is something missing, such as what if the parameter number does not match? What is the type conversion process? How to do it more generic like this call:
`{ "func_name":"BarSwap", "params":[ 0.1, 0.9 ]}`result:=string(reflectinvoke.InvokeByJson([]byte(jsonStr))
For a complete code example, see the code above GitHub.