dongluo1853 2017-12-04 03:22
浏览 35
已采纳

使用反射解码参数

This is a followup question to Function and argument unmarshalling in go?.

Given the following interface variable.

var args interface{}

Assuming as an example it contained these bytes:

[[74 111 104 110] [32 97 110 100 32 74 97 110 101]]

i.e. two strings "John", " and Jane"

And a function value obtained by MethodByName

f := reflect.ValueOf(s.functions).MethodByName("Hello")
if f.IsValid() {
  val := reflect.ValueOf(args)
  //  Do some kind of conversion...

  result := f.Call(val) // This won't compile. Wrong type.  How do I massage args of type interface{} into what's expected by the call.

}

I don't particularly care if it fails. I will capture the failure of the call with recover.

Here is a bit more detail:

var req struct {
    Ver      int
    MsgID    int
    FuncName string
    Args     interface{}
}

dec := codec.NewDecoder(frame, s.h)

err = dec.Decode(&req)
if err != nil {
    s.log.Println(err)
    break
}

fmt.Println("New Msg:")
fmt.Printf(" ver  : %d
", req.Ver)
fmt.Printf(" id   : %d
", req.MsgID)
fmt.Printf(" func : %s
", req.FuncName)

f := reflect.ValueOf(s.functions).MethodByName(req.FuncName)
if f.IsValid() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in f", r)
        }
    }()

    fmt.Println("Function is: ", req.FuncName)
    var callArgs []reflect.Value
    args := reflect.ValueOf(req.Args)
    t := f.Type()
    for i := 0; i < t.NumIn(); i++ {
        t := t.In(i)
        v := reflect.New(t).Elem()
        if i < args.Len() {
            // Convert arg to type of v and set.
            arg := args.Index(i)
            switch t.Kind() {
            case reflect.String:
                v.SetString(string(reflect.Value.Bytes(arg)))
            case reflect.Slice:
                if t.Elem() == reflect.TypeOf(byte(0)) {
                    v.SetBytes(reflect.Value.Bytes(arg))
                } else {
                    panic("not supported")
                }
            case reflect.Int:
                //i, err := strconv.ParseInt(string(arg), 10, 0)
                // if err != nil {
                //  panic("bad int")
                // }
                // v.SetInt(i)
            default:
                panic("not supported")
            }
        }
        // Collect arguments for the call below.
        callArgs = append(callArgs, v)
    }
    result := f.Call(callArgs)
    fmt.Println(result)

    val := reflect.ValueOf(req.Args)
    a := []reflect.Value{val}

    r := f.Call(a)
    fmt.Println("Returned", r[0], r[1])
}

Outputs:

New Msg: ver : 2 id : 1 func : Hello Function is: Hello Recovered in f reflect: call of reflect.Value.Bytes on interface Value

Note: This is an RPC API. I have a function name (see link at top of question) and some arguments that are passed in as an array. The arguments in my example here are strings but could anything that you could pass to a function. It's whatever the function requires. It's generic.

e.g.

Hello(name ...string) string

or

Add(n ...int) int

or

DoSomething(a string, b int, c bool)

etc

i.e. I'm unmarshalling the arguments and I don't know what they are. Except that I do know they will be passed into a slice and thrown into a variable Args which has the type interface{} I hope this makes sense now

  • 写回答

2条回答 默认 最新

  • dongyinglan8707 2017-12-04 03:47
    关注

    Try the following.

    The basic idea is to create a []reflect.Value for the call to reflect.Call by looping over the function arguments. For each argument, convert the incoming argument type to the type expected in the function call.

    var req = struct {
        Ver      int
        MsgID    int
        FuncName string
        Args     interface{}
    }{
        Args: []interface{}{[]byte("John"), "Jane", 123, "456"},
    }
    args := req.Args.([]interface{})
    
    var funcs Funcs
    f := reflect.ValueOf(funcs).MethodByName("Hello")
    var callArgs []reflect.Value
    t := f.Type()
    // For each function argument ...
    for i := 0; i < t.NumIn(); i++ {
        t := t.In(i)
        v := reflect.New(t).Elem()
        if i < len(args) {
            // Convert arg to type of v and set.
            arg := args[i]
            switch t.Kind() {
            case reflect.String:
                switch arg := arg.(type) {
                case string:
                    v.SetString(arg)
                case []byte:
                    v.SetString(string(arg))
                default:
                    panic("not supported")
                }
            case reflect.Slice:
                if t.Elem() != reflect.TypeOf(byte(0)) {
                    panic("not supported")
                }
                switch arg := arg.(type) {
                case string:
                    v.SetBytes([]byte(arg))
                case []byte:
                    v.SetBytes(arg)
                default:
                    panic("not supported")
                }
    
            case reflect.Int:
                switch arg := arg.(type) {
                case int:
                    v.SetInt(int64(arg))
                case string:
                    i, err := strconv.ParseInt(arg, 10, 0)
                    if err != nil {
                        panic("bad int")
                    }
                    v.SetInt(i)
                default:
                    panic("not supported")
                }
            default:
                panic("not supported")
            }
        }
        // Collect arguments for the call below.
        callArgs = append(callArgs, v)
    }
    
    result := f.Call(callArgs)
    fmt.Println(result)
    

    The snippet includes conversions for string, []byte and int types. Conversions for other types can be added.

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥15 想用@vueuse 把项目动态改成深色主题,localStorge里面的vueuse-color-scheme一开始就给我改成了dark,不知道什么原因(相关搜索:背景颜色)
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题