Go语言教程之边写边学:如何在HTTP客户端处理HTTP超时
在Go中,您可以借助net/http包处理HTTP超时。默认情况下,http.包提供的客户端类型未设置超时。但是,您可以使用http的Timeout字段设置超时。
下面是为HTTP请求设置5秒超时的示例:
import (
"net/http"
"time"
)
func main() {
// Create an http client with a timeout of 5 seconds
client := &http.Client{
Timeout: time.Second * 5,
}
// Send an HTTP request
resp, err := client.Get("http://example.com")
if err != nil {
// Handle the error
}
// Handle the response
defer resp.Body.Close()
// ...
}
在此示例中,我们创建一个http.client实例,并将其Timeout字段设置为time。第二个 * 5,持续时间为5秒。这意味着,如果请求完成时间超过5秒,客户端将取消请求并返回错误。
请注意,您可以通过在http上使用适当的方法为不同类型的HTTP请求(如GET、POST、PUT和DELETE)设置超时。
例如,您可以使用client.Post() 为HTTP POST请求设置超时。
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func main() {
// Create a new HTTP client with a timeout of 10 seconds
client := &http.Client{
Timeout: 10 * time.Second,
}
// Define the endpoints for the CRUD operations
http.HandleFunc("/create", createHandler(client))
http.HandleFunc("/read", readHandler(client))
http.HandleFunc("/update", updateHandler(client))
http.HandleFunc("/delete", deleteHandler(client))
// Start the server and log any errors
log.Fatal(http.ListenAndServe(":8080", nil))
}
func createHandler(client *http.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Set the request timeout to 5 seconds
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
// Make the request with the client
_, err := client.PostContext(ctx, "http://localhost:8080/create", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write the success message to the response
fmt.Fprint(w, "Create successful")
}
}
func readHandler(client *http.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Set the request timeout to 5 seconds
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
// Make the request with the client
_, err := client.GetContext(ctx, "http://localhost:8080/read")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write the success message to the response
fmt.Fprint(w, "Read successful")
}
}
func updateHandler(client *http.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Set the request timeout to 5 seconds
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
// Make the request with the client
_, err := client.PutContext(ctx, "http://localhost:8080/update", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write the success message to the response
fmt.Fprint(w, "Update successful")
}
}
func deleteHandler(client *http.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Set the request timeout to 5 seconds
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
// Make the request with the client
_, err := client.DeleteContext(ctx, "http://localhost:8080/delete")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write the success message to the response
fmt.Fprint(w, "Delete successful")
}
}
此代码创建一个超时为10秒的HTTP客户端,然后为CRUD操作定义四个终结点处理程序。每个处理程序使用请求的上下文将请求超时设置为5秒,然后使用HTTP客户端向相应的终结点发出请求。如果请求失败,则会在HTTP响应中写入错误响应。如果请求成功,则会在HTTP响应中写入一条成功消息。