Rake Rame
Rake Rame

Reputation: 19

When does go net/http return err (post request)

I am facing a very tricky question which I am unable to find the right answer for.

Let us use the below sample code for reference. Will the "err" not be a nil value when I get a 400 or 401 http error from the server? What http status codes result in err being returned (non nil value) ? 2xx, 4xx, 5xx ? Where do I find the documentation for this?

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    // The URL for the Google Books API, searching for "Pride and Prejudice"
    url := "https://httpbin.org/status/401"

    // Create a new HTTP client with default settings
    client := &http.Client{}

    // Create a new HTTP request
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        fmt.Println("Error creating request:", err)
        return
    }

    // Send the request and receive the response
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Error making API call:", err)
        return
    }
    defer resp.Body.Close() // Ensure the response body is closed after reading

    // Read the response body
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Error reading response:", err)
        return
    }

    // Print the response body as a string
    fmt.Println("Response:", string(body))
}

Trying to solve a bug in my project.

Upvotes: 1

Views: 97

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191831

https://pkg.go.dev/net/http#Client.Do

An error is returned if caused by client policy (such as CheckRedirect), or failure to speak HTTP (such as a network connectivity problem). A non-2xx status code doesn't cause an error.

Upvotes: 1

Related Questions