Go语言教程之边写边学:如何处理HTTP 错误
在Go中,可以使用net/http包来处理HTTP错误,该包为处理HTTP错误提供了内置支持。下面是一个示例代码片段,演示了如何在Go中处理HTTP错误:
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
// ...
}
在此代码片段中,我们使用http.Get函数向http://example.com发送GET请求。如果在请求过程中发生错误,我们会处理它并退出程序。如果响应状态码不是http.StatusOK(即200),我们处理错误并退出程序。否则,我们会根据需要处理响应。 您还可以使用http.Response.StatusCode字段和http.Response.Body字段。
下面是演示此方法的示例代码片段:
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
// ...
}
在此代码片段中,我们使用http.Get函数向http://example.com发送GET请求。如果在请求期间或读取响应正文时发生错误,我们会处理它并退出程序。然后,我们检查响应状态代码和响应正文是否存在错误。如果发生错误,我们会处理它并退出程序。否则,我们会根据需要处理响应。
系列文章