【问题标题】:API (almost) RESTFul variable response with GoLang使用 GoLang 的 API(几乎)RESTFul 变量响应
【发布时间】:2019-02-17 11:11:30
【问题描述】:

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

所有端点都可以响应一个或多个(数组)对象,即使 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 结构中的服务器响应方面解决这个问题的最佳策略。

【问题讨论】:

  • 您在 struct{Couint int; Customers json.RawMessage} 中解析响应,并根据 Count 将客户解组为结构或结构切片。
  • 现在我知道json.RawMessage,它非常强大。 THX

标签: json rest api go mapping


【解决方案1】:

我在使用新的 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 之前的答案是正确的,原始消息是最好的。

【讨论】:

    【解决方案2】:
    type ListResponse struct{
        Count int `json:"count"`
        Customers []Customer `json:"customers"`
    }
    
    type Customer struct{
    ID int               `json:"id"`
    VatNum string        `json:"vatnum"`
    Name string          `json:"name"`
    CountryId int        `country_id`
    }
    func main(){
        customer1 = Customer{1,"vat 1","name 1",1000}
        customer2 = Customer{2,"vat 2","name 2",1001}
        customers := make([]Customer,0,10)
        customers = append(customers,customer1,customer2)
        response = ListResponse{len(customers),customers}
        buf,_ = json.Marshal(response)
        fmt.Println(string(buf))
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-04
      • 1970-01-01
      • 2014-08-02
      • 2015-04-30
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      相关资源
      最近更新 更多