I have a software which I can not replace for various reasons and has an API that looks like RESTFul.
All EndPoints can respond with one or more (in array) objects, even if the RESTFul architecture says that it has to respond with an array of objects, if it only finds one, it returns the object without being wrapped in an array.
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
}
}
My problem is that I am making the client of this API and I do not know which is the best strategy to solve this problem in terms of mapping/parsing the server response in Golang structs.
I use this tool a lot when consuming new apis https://mholt.github.io/json-to-go/ if you copy paste your json you can get automated struts ie:
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"`
}
This is the single struct which the other one would just be an array of this.
I realized i misread your question. https://golang.org/pkg/encoding/json/#RawMessage The previous answer was right raw message is best.
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))
}