How do you handle HTTP errors in Go?
Example
package main
import (
"fmt"
"net/http"
)
func main() {
// send a GET request
resp, err := http.Get("http://example.com")
if err != nil {
// handle error
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// check for errors in the response status code
if resp.StatusCode != http.StatusOK {
// handle error
fmt.Println("Error: unexpected status code:", resp.StatusCode)
return
}
// process the response
// ...
}
In this code snippet, we use the http.Get function to send a GET request to http://example.com. If an error occurs during the request, we handle it and exit the program. If the response status code is not http.StatusOK (i.e., 200), we handle the error and exit the program. Otherwise, we process the response as desired.
You can also handle errors in a more general way using the http.Response.StatusCode field and the http.Response.Body field. Here is an example code snippet that demonstrates this approach:
Example
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// send a GET request
resp, err := http.Get("http://example.com")
if err != nil {
// handle error
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
fmt.Println("Error reading response body:", err)
return
}
// check for errors in the response
if resp.StatusCode != http.StatusOK {
// handle error
fmt.Println("Error:", resp.StatusCode, string(body))
return
}
// process the response
// ...
}
In this code snippet, we use the http.Get function to send a GET request to http://example.com. If an error occurs during the request or while reading the response body, we handle it and exit the program. We then check the response status code and response body for errors. If an error occurs, we handle it and exit the program. Otherwise, we process the response as desired.