GoQuery 响应代码

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

GoQuery Response Code

问题

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

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

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

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

英文:

In GoQuery, if I create a snippet as follows:

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

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方法来实现。例如:

  1. res, err := http.Get(url)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. // 检查状态码是否为200(或者非403,或者其他你想要的状态码)
  6. if res.StatusCode == 200 {
  7. doc, err := goquery.NewDocumentFromResponse(res)
  8. if err != nil {
  9. log.Fatal(err)
  10. }
  11. // ...
  12. }
英文:

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.:

  1. res, err := http.Get(url)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. // Check for a 200 status (or a non-403, or whatever you want)
  6. if res.StatusCode == 200 {
  7. doc, err := goquery.NewDocumentFromResponse(res)
  8. if err != nil {
  9. log.Fatal(err)
  10. }
  11. // ...
  12. }

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:

确定