GoQuery 响应代码

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

GoQuery Response Code

问题

在GoQuery中,如果我创建了以下代码片段:

doc, err := goquery.NewDocument(s)
if err != nil {
    log.Fatal(err)
}

其中s是一个有效的URL,我可以看到错误字符串,但如果页面返回403错误,我该如何找出并停止代码运行,而不是让它继续运行?

在GoQuery中,有没有一种方法可以找到HTTP响应?

英文:

In GoQuery, if I create a snippet as follows:

    doc, err := goquery.NewDocument(s)
	if err != nil {
		log.Fatal(err)
	}                 

where s is a valid url, I can see the error string, but if the page is returning a 403, how do I find out and stop instead of letting my code run?

Is there a way to find the http response using Goquery?

答案1

得分: 1

我不认为NewDocument方法可以根据状态码来判断是否终止,但你可以使用NewDocumentFromResponse方法来实现。例如:

res, err := http.Get(url)
if err != nil {
    log.Fatal(err)
}

// 检查状态码是否为200(或者非403,或者其他你想要的状态码)
if res.StatusCode == 200 {
    doc, err := goquery.NewDocumentFromResponse(res)
    if err != nil {
        log.Fatal(err)
    }
    // ...
}
英文:

I don't think that NewDocument gives you the chance to bail based on a status code, but you can use NewDocumentFromResponse instead. E.g.:

res, err := http.Get(url)
if err != nil {
	log.Fatal(err)
}

// Check for a 200 status (or a non-403, or whatever you want)
if res.StatusCode == 200 {
	doc, err := goquery.NewDocumentFromResponse(res)
	if err != nil {
		log.Fatal(err)
	}
	// ...
}

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

发表评论

匿名网友

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

确定