【发布时间】:2015-08-16 18:22:18
【问题描述】:
我有一些用 Go 编写的代码(见下文),它应该“扇出”HTTP 请求,然后整理/汇总详细信息。
我是 golang 的新手,所以希望我成为一个 nOOb 并且我的知识是有限的
程序的输出目前是这样的:
{
"Status":"success",
"Components":[
{"Id":"foo","Status":200,"Body":"..."},
{"Id":"bar","Status":200,"Body":"..."},
{"Id":"baz","Status":404,"Body":"..."},
...
]
}
有一个正在运行的本地服务器故意变慢(休眠 5 秒,然后返回响应)。但我列出了其他网站(参见下面的代码),有时也会触发错误(如果它们出错,那很好)。
我现在的问题是如何最好地处理这些错误,特别是“超时”相关的错误;因为我不确定如何识别失败是超时还是其他错误?
目前我一直收到一个全面错误:
Get http://localhost:8080/pugs: read tcp 127.0.0.1:8080: use of closed network connection
http://localhost:8080/pugs 通常是失败的 url(希望是超时!)。但是正如您从代码(如下)中看到的那样,我不确定如何确定错误代码与超时有关,也不确定如何访问响应的状态代码(我目前只是将其设置为@987654326 @ 但显然这是不对的 - 如果服务器出错,我会期待像 500 这样的状态代码,显然我想在我发回的汇总响应中反映这一点。
完整的代码可以在下面看到。任何帮助表示赞赏。
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
)
type Component struct {
Id string `json:"id"`
Url string `json:"url"`
}
type ComponentsList struct {
Components []Component `json:"components"`
}
type ComponentResponse struct {
Id string
Status int
Body string
}
type Result struct {
Status string
Components []ComponentResponse
}
var overallStatus string = "success"
func main() {
var cr []ComponentResponse
var c ComponentsList
b := []byte(`{"components":[{"id":"local","url":"http://localhost:8080/pugs"},{"id":"google","url":"http://google.com/"},{"id":"integralist","url":"http://integralist.co.uk/"},{"id":"sloooow","url":"http://stevesouders.com/cuzillion/?c0=hj1hfff30_5_f&t=1439194716962"}]}`)
json.Unmarshal(b, &c)
var wg sync.WaitGroup
timeout := time.Duration(1 * time.Second)
client := http.Client{
Timeout: timeout,
}
for i, v := range c.Components {
wg.Add(1)
go func(i int, v Component) {
defer wg.Done()
resp, err := client.Get(v.Url)
if err != nil {
fmt.Printf("Problem getting the response: %s\n", err)
cr = append(cr, ComponentResponse{
v.Id,
404,
err.Error(),
})
} else {
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Problem reading the body: %s\n", err)
}
cr = append(cr, ComponentResponse{
v.Id,
resp.StatusCode,
string(contents),
})
}
}(i, v)
}
wg.Wait()
j, err := json.Marshal(Result{overallStatus, cr})
if err != nil {
fmt.Printf("Problem converting to JSON: %s\n", err)
return
}
fmt.Println(string(j))
}
【问题讨论】:
-
很可能与您的问题无关,但您有一个附加到
cr的数据竞争。你不能在没有同步的情况下从多个 goroutine 中写入相同的变量。您可能希望使用race detector 构建/运行。 -
感谢您的评论。我会改用频道+我会调查那个种族检测器:-)
-
如果客户端调用返回错误,则没有状态码,因为没有完整的http请求。那时你对错误无能为力,但在 go1.5 中,client.Timeout 至少会在 net.Error 中返回更好的消息。
-
this 会帮忙吗?
-
似乎 1.5 的发布日期已过期(截至 2015 年 8 月 17 日)。我将不得不坚持看看这是否确实解决了问题。
标签: go timeout http-status-codes