Golang calls the specified method of the struct and returns the JSON result by reflection using a JSON string

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.