答案:本文介绍了Golang中使用net/http库处理HTTP请求的常见操作。1. 发送GET、POST请求并读取响应;2. 使用http.NewRequest自定义请求头;3. 设置客户端超时时间;4. 处理响应状态码,如200表示成功,404表示资源未找到;5. 通过url.Values构建带查询参数的URL;6. 使用http.Cookie设置和获取Cookie,实现会话管理。

Golang的
net/http库提供了构建HTTP客户端的强大功能,本文将展示一些实用的请求示例,帮助你快速上手。
解决方案:
package main
import (
"fmt"
"io"
"log"
"net/http"
"strings"
)
func main() {
// 1. GET 请求示例
getURL := "https://httpbin.org/get"
getResp, err := http.Get(getURL)
if err != nil {
log.Fatalf("GET request failed: %v", err)
}
defer getResp.Body.Close()
getResponseBody, err := io.ReadAll(getResp.Body)
if err != nil {
log.Fatalf("Error reading GET response body: %v", err)
}
fmt.Println("GET Response:", string(getResponseBody))
// 2. POST 请求示例
postURL := "https://httpbin.org/post"
postData := strings.NewReader(`{"key": "value"}`)
postResp, err := http.Post(postURL, "application/json", postData)
if err != nil {
log.Fatalf("POST request failed: %v", err)
}
defer postResp.Body.Close()
postResponseBody, err := io.ReadAll(postResp.Body)
if err != nil {
log.Fatalf("Error reading POST response body: %v", err)
}
fmt.Println("POST Response:", string(postResponseBody))
// 3. 自定义请求头示例
client := &http.Client{}
req, err := http.NewRequest("GET", getURL, nil)
if err != nil {
log.Fatalf("Error creating request: %v", err)
}
req.Header.Set("X-Custom-Header", "MyValue")
customResp, err := client.Do(req)
if err != nil {
log.Fatalf("Custom header request failed: %v", err)
}
defer customResp.Body.Close()
customResponseBody, err := io.ReadAll(customResp.Body)
if err != nil {
log.Fatalf("Error reading custom header response body: %v", err)
}
fmt.Println("Custom Header Response:", string(customResponseBody))
// 4. 设置超时时间
clientWithTimeout := &http.Client{
Timeout: time.Second * 5, // 设置 5 秒超时
}
timeoutURL := "https://httpbin.org/delay/10" // 模拟一个延迟10秒的请求
timeoutResp, err := clientWithTimeout.Get(timeoutURL)
if err != nil {
log.Printf("Timeout request failed: %v", err)
} else {
defer timeoutResp.Body.Close()
timeoutResponseBody, err := io.ReadAll(timeoutResp.Body)
if err != nil {
log.Fatalf("Error reading timeout response body: %v", err)
}
fmt.Println("Timeout Response:", string(timeoutResponseBody))
}
}如何处理HTTP响应的状态码?
HTTP响应状态码是服务器返回的,用来表示请求的结果。常见的处理方式包括:
-
检查状态码: 使用
resp.StatusCode
获取状态码,并与http.StatusOK
等常量比较。 - 错误处理: 对于非2xx的状态码,通常需要记录日志、重试请求或向用户显示错误信息。
-
重定向处理: 对于3xx的状态码,可能需要根据
Location
头部进行重定向。net/http
默认会自动处理一些重定向,但复杂的场景可能需要手动处理。 - 自定义错误: 可以根据业务逻辑,自定义错误类型来处理特定的状态码。
resp, err := http.Get("https://httpbin.org/status/404")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
bodyString := string(bodyBytes)
fmt.Println(bodyString)
} else if resp.StatusCode == http.StatusNotFound {
fmt.Println("Resource not found")
} else {
fmt.Printf("Unexpected status code: %d\n", resp.StatusCode)
}如何发送带有查询参数的GET请求?
发送带有查询参数的GET请求,可以通过
url.Values来构建URL,然后使用
http.NewRequest创建请求。
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
)
func main() {
baseURL := "https://httpbin.org/get"
// 构建查询参数
params := url.Values{}
params.Add("param1", "value1")
params.Add("param2", "value2")
// 将查询参数添加到URL
fullURL := baseURL + "?" + params.Encode()
// 创建HTTP客户端
client := &http.Client{}
// 创建GET请求
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
log.Fatalf("Error creating request: %v", err)
}
// 发送请求
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Error sending request: %v", err)
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error reading response: %v", err)
}
fmt.Println("Response:", string(body))
}
如何处理HTTP请求中的Cookie?
Cookie的处理涉及到设置和获取。
-
设置Cookie: 使用
http.Cookie
结构体创建Cookie,然后使用http.ResponseWriter
的Header().Set("Set-Cookie", cookie.String())方法设置Cookie。在客户端请求中,服务器可以通过响应头来设置 Cookie。 -
获取Cookie: 在客户端,可以使用
Request.Cookie(name string)
方法获取指定的Cookie。如果需要获取所有Cookie,可以使用Request.Cookies()
方法。
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func setCookieHandler(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "my_cookie",
Value: "cookie_value",
Path: "/",
Domain: "localhost", // 实际应用中应设置为你的域名
Expires: time.Now().Add(24 * time.Hour),
Secure: false, // 如果是HTTPS,应设置为true
HttpOnly: true, // 防止客户端脚本访问
}
http.SetCookie(w, cookie)
fmt.Fprintln(w, "Cookie has been set")
}
func getCookieHandler(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("my_cookie")
if err != nil {
if err == http.ErrNoCookie {
fmt.Fprintln(w, "Cookie not found")
return
}
log.Println("Error getting cookie:", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "Cookie value: %s\n", cookie.Value)
}
func main() {
http.HandleFunc("/set_cookie", setCookieHandler)
http.HandleFunc("/get_cookie", getCookieHandler)
fmt.Println("Server listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}










