httpgogoquery

GoQuery Response Code


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?


Solution

  • 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)
        }
        // ...
    }