I have many API endpoints with same base data format. I want to get data from them and unmarshal response to specific struct
or format.
For example we have following endpoints and example responses:
GET /api1
{
"data": [
{"username": "Marcelo Roberts Sr."}
]
}
GET /api2
{
"list": [
{"id": "Vernon Effertz"}
]
}
Responses in my case is more complex. Anyway I want to convert this responses to one format. For example all of them use following struct:
type Res struct {
Identifier string `json:"identifier"`
}
I want to convert all of responses to an object from []Res
.
I use following code for converting each type:
func getData() (string, error) {
var response struct {
Data []struct {
Identifier string `json:"username"`
} `json:"data`
}
rawResp, err := http.Get("https://domain/api1")
if err != nil {
return "", err
}
byteResp, _ := io.ReadAll(rawResp.Body)
err = json.Unmarshal(byteResp, &response)
if err != nil {
return "", err
}
var prices = make(map[string]Price)
for _, obj := range response.Data. {
prices[obj.Username] = Res{
Identifier: obj.Identifier,
}
}
stsandardResponse, _ := json.Marshal(prices)
return string(stsandardResponse), nil
}
I have lots of endpoints like this. How can I simplify them and avoiding DRY ?
I know this functions just have different on 3 section. a) Label of nested struct b) Path of final struct Res
like data c) Where we should iterate on loop.
How can I design well ?