首页 > 解决方案 > 使用 GoLang 的 API(几乎)RESTFul 变量响应

问题描述

我有一个由于各种原因无法替换的软件,并且有一个看起来像 RESTFul 的 API。

所有 EndPoints 都可以响应一个或多个(数组中的)对象,即使 RESTFul 体系结构说它必须响应一个对象数组,如果它只找到一个对象,它就会返回对象而不被包装在数组中。

GET /customers?country_id=10000

{
  "count": 5,
  "customers": [
    { "id": 10000, "name": "Customer 10000", "vatnum": "123456789P", "country_id": 10000 },
    { "id": 10001, "name": "Customer 10001", "vatnum": "234567891P", "country_id": 10000 },
    { "id": 10002, "name": "Customer 10002", "vatnum": "345678912P", "country_id": 10000 },
    { "id": 10003, "name": "Customer 10003", "vatnum": "456789123P", "country_id": 10000 },
    { "id": 10004, "name": "Customer 10004", "vatnum": "567891234P", "country_id": 10000 }
  ]
}

GET /customers?vatnum=123456789P

{
  "count": 1,
  "customers": {
    "id": 10000,
    "name": "Customer 10000",
    "vatnum": "123456789P",
    "country_id": 10000
  }
}

我的问题是我正在制作这个 API 的客户端,我不知道在映射/解析 Golang 结构中的服务器响应方面解决这个问题的最佳策略是什么。

标签: jsonrestapigomapping

解决方案


我在使用新的 api 时经常使用这个工具 https://mholt.github.io/json-to-go/ 如果你复制粘贴你的 json 你可以获得自动化的 struts 即:

type AutoGenerated struct {
    Count     int `json:"count"`
    Customers struct {
        ID        int    `json:"id"`
        Name      string `json:"name"`
        Vatnum    string `json:"vatnum"`
        CountryID int    `json:"country_id"`
    } `json:"customers"`
}

这是单个结构,另一个只是这个数组。

我意识到我误读了你的问题。 https://golang.org/pkg/encoding/json/#RawMessage 之前的答案是正确的原始消息是最好的。


推荐阅读