douqiang6036 2018-05-22 06:27
浏览 87
已采纳

为每个GET请求创建一个新的JSON文件

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)

            }
        }
    }
}
  • 写回答

2条回答 默认 最新

  • dragon071111 2018-05-22 12:12
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?