如何从golang中的接口获取值

I need to get values from a serialized string which generated from php code

So I use a package named:php_serialize to unserialize the string and then got a result of interface{} type .

But I have no idea how to get values inside the result.

This is code:

package main

import (
    "github.com/yvasiyarov/php_session_decoder/php_serialize"
    "fmt"
)

func main() {
    // this string is generated from php code
    str := `a:3:{s:4:"name";s:3:"tom";s:3:"age";s:2:"23";s:7:"friends";a:2:{i:0;a:1:{s:4:"name";s:5:"jerry";}i:1;a:1:{s:4:"name";s:4:"jack";}}}`

    decoder := php_serialize.NewUnSerializer(str)

    if result, err := decoder.Decode(); err != nil {
        panic(err)
    } else {
        fmt.Println(result)
    }
}

The print result is :

map[name:tom age:23 friends:map[0:map[name:jerry] 1:map[name:jack]]]

This result is a php_serialize.PhpValue type, which is interface{} type

The next step is how to get values inside the result?

such as get the age field and value

Here some ways to access the data:

package main

import (
    "fmt"

    "github.com/yvasiyarov/php_session_decoder/php_serialize"
)

func main() {
    // this string is generated from php code
    str := `a:3:{s:4:"name";s:3:"tom";s:3:"age";s:2:"23";s:7:"friends";a:2:{i:0;a:1:{s:4:"name";s:5:"jerry";}i:1;a:1:{s:4:"name";s:4:"jack";}}}`

    decoder := php_serialize.NewUnSerializer(str)

    result, err := decoder.Decode()
    if err != nil {
        panic(err)
    }
    fmt.Println(result)

    // simple assert
    t := result.(php_serialize.PhpArray)
    // use php_seriale build in function to get string
    strVal := php_serialize.PhpValueString(t["name"])
    fmt.Println(strVal)

    // type switch in case of different valid types
    switch t := result.(type) {
    default:
        fmt.Printf("unexpected type %T
", t) // %T prints whatever type t has
    case php_serialize.PhpArray:
        fmt.Println(t)
        fmt.Println(t["name"])
        fmt.Println(t["age"])

        // should be done recursively...
        switch f := t["friends"].(type) {
        default:
            fmt.Printf("unexpected type %T
", f) // %T prints whatever type t has
        case php_serialize.PhpArray:
            fmt.Println(f)
            fmt.Println(f[0])
            fmt.Println(f[1])
        }
    }
}

I hope this gives you some ideas.

Basic concept

  • php_serialize has built in functions to convert primitives.
  • Variable structures are represented with built in types which need to be used to access the structure.

You must assert the result to map[string]interface:

mResult := result.(map[string]interface{})
fmt.Println(mResult["name"])

And once more assertion for friends:

mFriends := mResult["friends"].(map[int]map[string]interface{}) 

Then use it: mFriends[0]["name"]