Home > Back-end >  How to get data from external api using GO?
How to get data from external api using GO?

Time:05-25

I have external data I need to get data from it and this result from an API endpoint

{
  "data": [
    {
      "id": 30002005,
      "name": "test",
      "info": "{"Version":"7.0.484","CompanyName":"test"}",
    },
    ......
  ]
}

I need to get this data and reformat it to my case (put the data into struct then do whatever i need).

The go code:

type OldData struct {
    Id            string `json:"id"`
    Name          string `json:"name"`
}

func Index() {

    url := "https://exmaple.com/api/posts"
    var bearer = "Bearer XXXXXX"

    req, err := http.NewRequest("GET", url, nil)
    req.Header.Add("Authorization", bearer)

    client := &http.Client{}

    resp, err := client.Do(req)
    if err != nil {
        log.Println(err)
    }

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {
        log.Println(err)
    }

    var record OldData

    json.Unmarshal(body, &record)

    fmt.Println(record)
}

The result of fmt.Println(record) is { }

Update

I create thrid for info :

type OldData struct {
    Id            string `json:"id"`
    Name          string `json:"name"`
    Info          string `json:"info"`
}

type Info struct {
    Version     string `json:"Version"`
    CompanyName string `json:"CompanyName"`
}

CodePudding user response:

In the JSON there is an array, named data. You're trying to unmarshal it to a single struct. Try to define a struct which has a data field which is a slice:

type OldData struct {
    Id            string `json:"id"`
    Name          string `json:"name"`
}

type OldDataItems struct {
    Data []OldData `json:"data"`
}

Now try to unmarshal into an instance of OldDataItems.

  • Related