Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

First of all, this is my first non-dummy program using Go. Any recommendation will be appreciated.

Code description:

I want to retrieve all the information from an API where the information is being paginated. So I want to iterate through all the pages in order to get all the information.

This is what I did so far:

I have the these two functions:

func request(requestData *RequestData) []*ProjectsResponse {

    client := &http.Client{
        Timeout: time.Second * 10,
    }

    projects := []*ProjectsResponse{}
    innerRequest(client, requestData.URL, projects)

    return projects
}

func innerRequest(client *http.Client, URL string, projects []*ProjectsResponse) {

    if URL == "" {
        return
    }

    req, err := http.NewRequest("GET", URL, nil)
    if err != nil {
        log.Printf("Request creation failed with error %s
", err)
    }
    req.Header.Add("Private-Token", os.Getenv("API_KEY"))

    res, err := client.Do(req)
    log.Printf("Executing request: %s", req.URL)

    if err != nil {
        log.Printf("The HTTP request failed with error %s
", err)
    }
    data, _ := ioutil.ReadAll(res.Body)
    var response ProjectsResponse
    err = json.Unmarshal(data, &response)

    if err != nil {
        log.Printf("Unmarshalling failed with error %s
", err)
    }

    projects = append(projects, &response)
    pagingData := getPageInformation(res)
    innerRequest(client, pagingData.NextLink, projects)
}

Undesired behavior:

The values in the projects []*ProjectsResponse array are being appended on each iteration of the recursion, but when the recursion ends I get an empty array list. So, somehow after the innerRequests ends, in the project variable inside the request method I get nothing.

Hope somebody and spot my mistake. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
148 views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...