答案:本文介绍了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
解决方案:
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响应状态码是服务器返回的,用来表示请求的结果。常见的处理方式包括:
resp.StatusCode
http.StatusOK
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请求,可以通过
url.Values
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))
}
Cookie的处理涉及到设置和获取。
http.Cookie
http.ResponseWriter
Header().Set("Set-Cookie", cookie.String())Request.Cookie(name string)
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))
}
以上就是Golang net/http库HTTP客户端请求示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号