从golang数据库查询后收到304代码。

huangapple go评论62阅读模式
英文:

Receiving 304 code after query from DB golang

问题

我正在尝试实现一个API,首先创建一个会话,然后使用GET请求查询该会话。有时候我会得到一个304 Not Modified的响应代码,意味着结果自上次轮询以来没有被修改,但这对我来说似乎是随机的。在这种情况下,我无法将响应保存到Golang结构中,这让我非常沮丧。你有什么见解,可能是什么问题呢?谢谢!

client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("GET", url, nil)
q := req.URL.Query()
q.Add("apiKey", apiKey)
q.Add("sortorder", "asc")
req.URL.RawQuery = q.Encode()

if err != nil {
    panic(err)
}
req.Header.Set("ACCEPT", "application/json")
resp, err := client.Do(req)
if err != nil {
    panic(err)
}

defer resp.Body.Close()
if resp.StatusCode == 200{
    if err != nil {
        panic(err)
    }
}else{
    fmt.Println(resp.StatusCode)
}
data, err := ioutil.ReadAll(resp.Body)

return []byte(data)
英文:

I am trying to implement an API at the moment, in the first step a session is created, and after this sesson is queried with a get request. Sometimes I get a response code of 304 Not Modified – the results have not been modified since the last poll, and it seems to be all random to me. In this case I am unable to save the response into a Golang structure. It is very frustrating. Do you have any insights what could be the problem? Thanks!

client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("GET", url, nil)
q := req.URL.Query()
q.Add("apiKey", apiKey)
q.Add("sortorder", "asc")
req.URL.RawQuery = q.Encode()

if err != nil {
	panic(err)
}
req.Header.Set("ACCEPT", "application/json")
resp, err := client.Do(req)
if err != nil {
	panic(err)
}

defer resp.Body.Close()
if resp.StatusCode == 200{
	if err != nil {
		panic(err)
	}
}else{
	fmt.Println(resp.StatusCode)
}
data, err := ioutil.ReadAll(resp.Body)

return []byte(data)

答案1

得分: 1

你们也在实现服务器吗?还是只有客户端?你们控制服务器吗?如果不控制服务器,你们可能需要处理304未修改状态码。如果服务器告诉你资源未被修改,那会很好,因为你可以绕过一些处理过程。

英文:

Are implementing the server too? Or just a client? Do you control the server? If you don't then you'll probably have to handle 304 not modified. It could be nice if the server tells you the resource has not been modified, because you may be able to short circuit some processing.

答案2

得分: 0

好的,问题已经通过等待1秒并重新轮询解决了。

英文:

Okay, problem has been solved by waiting for 1 second and polling again.

huangapple
  • 本文由 发表于 2016年12月25日 06:53:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/41317413.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定