here is my problem which I am confronted with. I am currently taking the data from an API with its format (I can't change it like that). So I have created a new structure to take the data and to change just the titles (in my case: it would be to change "name" by "nickname". But problem is that I block in my for loop to replace name by nickname. If you have any questions or solutions to give, I'm welcome ;)
My structure (from ItemsResponse to Tools : this is the format requested by the API and the champion structure corresponds to the change I want to make on my own api
type ItemsResponse struct {
Items []Brawler `json:"items"`
}
type Brawler struct {
ID int `json:"id"`
Username string `json:"Name"`
StarPowers []Powers `json:"starPowers"`
Gadgets []Tools `json:"gadgets"`
}
type Powers struct {
ID int `json:"id"`
Name string `json:"name"`
}
type Tools struct {
ID int `json:"id"`
Name string `json:"name"`
}
type Champion struct {
Id int `json:"id"`
NickName string `json:"nickname"`
}
My function to get the data from the api :
func getChampions(w http.ResponseWriter, r *http.Request) {
// get response from external API through resty library
client := resty.New()
var items ItemsResponse
resp, err := client.R().
SetHeader("Authorization", "application/json").
SetAuthToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6IjljYWJlNjNiLWI4ZTQtNGZjNy1iMTBlLWVhMTExOTBmMGJkZSIsImlhdCI6MTY1NTcxMzcyMiwic3ViIjoiZGV2ZWxvcGVyL2M3OTZmM2MxLTE4ZTktNjE0YS0wY2M3LWMwMWIyNTQ2ZDViYiIsInNjb3BlcyI6WyJicmF3bHN0YXJzIl0sImxpbWl0cyI6W3sidGllciI6ImRldmVsb3Blci9zaWx2ZXIiLCJ0eXBlIjoidGhyb3R0bGluZyJ9LHsiY2lkcnMiOlsiMTc4LjIwLjUwLjIwOSJdLCJ0eXBlIjoiY2xpZW50In1dfQ.pbdssmUbaGtoUTKgNOPmspo2gOdtZt7wrgQj3JA1xP8StdKlsg0tAz1iDygAjupUuhjE7ZoHDctNI05vJgwlsw").
Get("https://api.brawlstars.com/v1/brawlers")
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
// unmarshall struct
json.Unmarshal(resp.Body(), &items)
fmt.Println(items)
//sort items
champions := sortBrawler(items.Items)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(items)
}
My function with the for loop or I am stuck :
func sortBrawler(brawlers []Brawler) []Champion {
var champions []Champion
// for each brawler we create a champion with the same name as nickname and add it
// to the champions lists
for i := range brawlers {
// create a champion
var champ Champion
// add a champion to champions array
champions = append(champions, champ)
}
return champions
}
Result of what I get (without making any changes just by respecting their format) :
{
"items": [
{
"id": 16000000,
"Name": "SHELLY",
"starPowers": [
{
"id": 23000076,
"name": "SHELL SHOCK"
},
{
"id": 23000135,
"name": "BAND-AID"
}
],
"gadgets": [
{
"id": 23000255,
"name": "FAST FORWARD"
},
{
"id": 23000288,
"name": "CLAY PIGEONS"
}
]
},