golang 中特定于平台的反序列化?

Platform specific deserialisation in golang?

我正在使用 REST API 并取回一些数据。昨天我遇到了一个有趣的行为。我还没有理解它背后的确切原因。这就是我想在这里寻找的。 对于看起来像 -

的有效载荷
{
    "id": 2091967,
    "first_name": "",
    "last_name": "",
    "email": "",
    "telephone": "",
    "timezone": "",
    "weekly_capacity": "",
    "has_access_to_all_future_projects": false,
    "is_contractor": false,
    "is_admin": false,
    "is_project_manager": false,
    "can_see_rates": false,
    "can_create_projects": false,
    "can_create_invoices": false,
    "is_active": false,
    "created_at": "2018-04-16T00:48:30Z",
    "updated_at": "2018-11-07T22:47:43Z",
    "default_hourly_rate": null,
    "cost_rate": null,
    "roles": [
        "blah"
    ],
    "avatar_url": ""
}

我使用了如下所示的函数来获取电子邮件 -

func GetUserEmail(userID int) string {
    resp := getFromSomething("https://something/users/" + strconv.Itoa(userID))
    var result map[string]string

    json.NewDecoder(resp.Body).Decode(&result)
    log.Printf("userEmail: %s", result["email"])
    return result["email"]
}

代码在我的 mac 上完美运行,就像我构建它一样 - env GOOS=linux go build -ldflags="-s -w" -o bin/something cmd/main.go 但是,它无法反序列化,并且在使用相同的构建命令时没有在 EC2 实例上打印任何内容。

但后来,我将 var result map[string]string 更改为 var result map[string]interface{},它在我的 EC2 实例和 mac 上都有效。

我还必须在最后对 interface{} 对象进行类型转换,然后再返回它。

func GetUserEmail(userID int) string {
    resp := getFromSomething("https://something/users/" + strconv.Itoa(userID))
    var result map[string]interface{}

    json.NewDecoder(resp.Body).Decode(&result)
    log.Printf("userEmail: %s", result["email"])
    return result["email"].(string)
}

有没有人见过这样的事情?或者,有人知道为什么会这样吗?

我知道 var result map[string]interface{} 总是可以更好地表示负载,但我的问题是 - 为什么 var result map[string]string 的早期表示在 Mac 而不是在 EC2 上?

Mac - go version go1.11.2 darwin/amd64 上的 Go 版本,EC2 上的版本是 go version go1.10.3 linux/amd64

始终检查并处理错误。

解码返回的错误说明了问题。该应用程序正在尝试将数字、布尔值和数组解码为字符串值。

var v map[string]string
err := json.NewDecoder(data).Decode(&v) // data is the JSON document from the question
fmt.Println(err)  // prints json: cannot unmarshal number into Go value of type string

Run it on the Playground.

此问题不是特定于平台的。我有几个猜测,为什么你会看到不同的结果:

  • 在不同的平台上测试时使用了不同的 JSON 文档。
  • 问题指出命令 env GOOS=linux go build -ldflags="-s -w" -o bin/something cmd/main.go 用于构建 Mac 版本,但此命令不会构建可在 Mac 上执行的二进制文件。也许您 运行 不是您认为自己的代码 运行。

要么解码为您发现的 map[string]interface{},要么解码为具有您想要的一个字段的结构:

var v struct{ Email string }
if err := json.NewDecoder(data).Decode(&v); err != nil {
    // handle error
}
fmt.Println(v.Email) // prints the decoded email value.

Run it on the Playground.