Gordon Soh
Gordon Soh

Reputation: 23

Create a new JSON file for every GET request

Background story: I'm retrieving details using a GET method. I managed to get the program to parse the output given by the server into a JSON file titled "output.json".

Problem: Every time I make different requests, the output will overwrite any previous content in the output.json file. Is it possible to make a new JSON file for every request? I am rather new to GoLang and any help will be very useful :)

Note: I am only showing the method that is being used to call the API, if need to, I will show the rest of my code.

Here is my method used:

func render(endpoint string, w http.ResponseWriter, r *http.Request) {
    // check if request has cookie set
    if cookie, err := r.Cookie(COOKIE_NAME); err != nil {
        // else redirect to OAuth Authorization EP
        redirectToOAuth(w, r, endpoint)
    } else {
        session := cookie.Value
        accessToken := sessions[session]

        // pipe api endpoint
        ep := fmt.Sprintf("%s/%s", fidorConfig.FidorApiUrl, endpoint)
        if api_req, err := http.NewRequest("GET", ep, nil); err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
        } else {
            api_req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
            api_req.Header.Set("Accept", "application/vnd.fidor.de; version=1,text/json") 

            client := &http.Client{}
            if api_resp, err := client.Do(api_req); err != nil {
                w.WriteHeader(500)
                w.Write([]byte(err.Error()))
            } else {
                if api_resp.StatusCode == 401 { // token probably expired
                    handleLogout(w, r, endpoint)
                    return
                }

                w.Header().Set("Content-Type", "application/json")
                w.WriteHeader(api_resp.StatusCode)


                defer api_resp.Body.Close()
                out, err := os.Create("output.json")
                if err != nil {
                    // panic?
                }
                defer out.Close()
                io.Copy(out, api_resp.Body)

            }
        }
    }
}

Upvotes: 1

Views: 577

Answers (2)

leninhasda
leninhasda

Reputation: 1740

If you want to append time in your filename (like @Florian suggested), you can do something like this when you are creating file:

out, err := os.Create(fmt.Sprintf("output-%d.json", time.Now().Unix()))
// filename => output-1257894000.json

Here time.Now().Unix() returns the number of seconds elapsed since January 1, 1970 UTC (aka Unix time). So each time it will create different json file.

More info about time: https://golang.org/pkg/time/#Time.Unix

Upvotes: 1

Florian
Florian

Reputation: 187

If you don't want your file to be overwritten you can either give the file a different name (for example by appending the current time using time.Now()) or you can append the output to the file, so the output.json contains all json files.

Upvotes: 0

Related Questions