Go学习笔记-HTTP编程

HTTP编程是现代Web开发的核心。Go语言内置了强大的net/http包,提供了完整的HTTP客户端和服务器功能,支持RESTful API、中间件、路由等特性。

HTTP服务器基础

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "log"
    "net/http"
    "strconv"
    "time"
)

// 1. 基本HTTP服务器
func basicHTTPServer() {
    fmt.Println("=== 基本HTTP服务器 ===")
    
    // 简单的处理函数
    helloHandler := func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World! 当前时间: %s", time.Now().Format("2006-01-02 15:04:05"))
    }
    
    // 注册路由
    http.HandleFunc("/hello", helloHandler)
    
    // 处理根路径
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path != "/" {
            http.NotFound(w, r)
            return
        }
        
        html := `
        <!DOCTYPE html>
        <html>
        <head>
            <title>Go HTTP服务器</title>
            <meta charset="UTF-8">
        </head>
        <body>
            <h1>欢迎使用Go HTTP服务器</h1>
            <p>可用的端点:</p>
            <ul>
                <li><a href="/hello">/hello</a> - 简单问候</li>
                <li><a href="/time">/time</a> - 当前时间</li>
                <li><a href="/api/users">/api/users</a> - 用户API</li>
            </ul>
        </body>
        </html>
        `
        w.Header().Set("Content-Type", "text/html; charset=utf-8")
        fmt.Fprint(w, html)
    })
    
    // 时间端点
    http.HandleFunc("/time", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        response := map[string]interface{}{
            "timestamp": time.Now().Unix(),
            "datetime":  time.Now().Format("2006-01-02 15:04:05"),
            "timezone":  "UTC",
        }
        json.NewEncoder(w).Encode(response)
    })
    
    fmt.Println("服务器启动在 http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

// 2. 处理不同HTTP方法
func httpMethodsHandler() {
    http.HandleFunc("/api/data", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        
        switch r.Method {
        case http.MethodGet:
            // GET请求 - 获取数据
            data := map[string]interface{}{
                "message": "这是GET请求的响应",
                "method":  "GET",
                "path":    r.URL.Path,
                "query":   r.URL.Query(),
            }
            json.NewEncoder(w).Encode(data)
            
        case http.MethodPost:
            // POST请求 - 创建数据
            body, err := io.ReadAll(r.Body)
            if err != nil {
                http.Error(w, "读取请求体失败", http.StatusBadRequest)
                return
            }
            defer r.Body.Close()
            
            response := map[string]interface{}{
                "message": "这是POST请求的响应",
                "method":  "POST",
                "body":    string(body),
                "created": true,
            }
            w.WriteHeader(http.StatusCreated)
            json.NewEncoder(w).Encode(response)
            
        case http.MethodPut:
            // PUT请求 - 更新数据
            body, err := io.ReadAll(r.Body)
            if err != nil {
                http.Error(w, "读取请求体失败", http.StatusBadRequest)
                return
            }
            defer r.Body.Close()
            
            response := map[string]interface{}{
                "message": "这是PUT请求的响应",
                "method":  "PUT",
                "body":    string(body),
                "updated": true,
            }
            json.NewEncoder(w).Encode(response)
            
        case http.MethodDelete:
            // DELETE请求 - 删除数据
            response := map[string]interface{}{
                "message": "这是DELETE请求的响应",
                "method":  "DELETE",
                "deleted": true,
            }
            json.NewEncoder(w).Encode(response)
            
        default:
            // 不支持的方法
            w.WriteHeader(http.StatusMethodNotAllowed)
            json.NewEncoder(w).Encode(map[string]string{
                "error": "方法不被允许",
                "method": r.Method,
            })
        }
    })
}

// 3. 用户管理API示例
type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
    Age   int    `json:"age"`
}

var users = []User{
    {ID: 1, Name: "张三", Email: "zhangsan@example.com", Age: 30},
    {ID: 2, Name: "李四", Email: "lisi@example.com", Age: 25},
    {ID: 3, Name: "王五", Email: "wangwu@example.com", Age: 35},
}

var nextUserID = 4

func userAPIHandlers() {
    // 获取所有用户
    http.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        
        switch r.Method {
        case http.MethodGet:
            json.NewEncoder(w).Encode(map[string]interface{}{
                "users": users,
                "total": len(users),
            })
            
        case http.MethodPost:
            var newUser User
            if err := json.NewDecoder(r.Body).Decode(&newUser); err != nil {
                http.Error(w, "无效的JSON数据", http.StatusBadRequest)
                return
            }
            
            // 验证必填字段
            if newUser.Name == "" || newUser.Email == "" {
                http.Error(w, "姓名和邮箱是必填字段", http.StatusBadRequest)
                return
            }
            
            // 分配ID并添加用户
            newUser.ID = nextUserID
            nextUserID++
            users = append(users, newUser)
            
            w.WriteHeader(http.StatusCreated)
            json.NewEncoder(w).Encode(map[string]interface{}{
                "message": "用户创建成功",
                "user":    newUser,
            })
            
        default:
            http.Error(w, "方法不被允许", http.StatusMethodNotAllowed)
        }
    })
    
    // 获取单个用户
    http.HandleFunc("/api/users/", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        
        // 提取用户ID
        path := r.URL.Path
        if len(path) <= len("/api/users/") {
            http.Error(w, "缺少用户ID", http.StatusBadRequest)
            return
        }
        
        userIDStr := path[len("/api/users/"):]
        userID, err := strconv.Atoi(userIDStr)
        if err != nil {
            http.Error(w, "无效的用户ID", http.StatusBadRequest)
            return
        }
        
        // 查找用户
        var foundUser *User
        var userIndex int
        for i, user := range users {
            if user.ID == userID {
                foundUser = &user
                userIndex = i
                break
            }
        }
        
        if foundUser == nil {
            http.Error(w, "用户不存在", http.StatusNotFound)
            return
        }
        
        switch r.Method {
        case http.MethodGet:
            json.NewEncoder(w).Encode(foundUser)
            
        case http.MethodPut:
            var updatedUser User
            if err := json.NewDecoder(r.Body).Decode(&updatedUser); err != nil {
                http.Error(w, "无效的JSON数据", http.StatusBadRequest)
                return
            }
            
            // 保持原有ID
            updatedUser.ID = userID
            users[userIndex] = updatedUser
            
            json.NewEncoder(w).Encode(map[string]interface{}{
                "message": "用户更新成功",
                "user":    updatedUser,
            })
            
        case http.MethodDelete:
            // 删除用户
            users = append(users[:userIndex], users[userIndex+1:]...)
            
            json.NewEncoder(w).Encode(map[string]interface{}{
                "message": "用户删除成功",
                "id":      userID,
            })
            
        default:
            http.Error(w, "方法不被允许", http.StatusMethodNotAllowed)
        }
    })
}

// 4. 中间件示例
func loggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        
        // 记录请求信息
        log.Printf("开始处理请求: %s %s", r.Method, r.URL.Path)
        
        // 调用下一个处理器
        next(w, r)
        
        // 记录响应信息
        duration := time.Since(start)
        log.Printf("请求处理完成: %s %s (耗时: %v)", r.Method, r.URL.Path, duration)
    }
}

func corsMiddleware(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // 设置CORS头
        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
        
        // 处理预检请求
        if r.Method == http.MethodOptions {
            w.WriteHeader(http.StatusOK)
            return
        }
        
        next(w, r)
    }
}

// 5. 文件上传处理
func fileUploadHandler() {
    http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
        if r.Method != http.MethodPost {
            http.Error(w, "只支持POST方法", http.StatusMethodNotAllowed)
            return
        }
        
        // 解析multipart表单
        err := r.ParseMultipartForm(10 << 20) // 10MB最大内存
        if err != nil {
            http.Error(w, "解析表单失败", http.StatusBadRequest)
            return
        }
        
        // 获取上传的文件
        file, header, err := r.FormFile("file")
        if err != nil {
            http.Error(w, "获取文件失败", http.StatusBadRequest)
            return
        }
        defer file.Close()
        
        // 读取文件内容
        fileContent, err := io.ReadAll(file)
        if err != nil {
            http.Error(w, "读取文件失败", http.StatusInternalServerError)
            return
        }
        
        // 响应上传结果
        w.Header().Set("Content-Type", "application/json")
        response := map[string]interface{}{
            "message":  "文件上传成功",
            "filename": header.Filename,
            "size":     len(fileContent),
            "type":     header.Header.Get("Content-Type"),
        }
        json.NewEncoder(w).Encode(response)
        
        log.Printf("文件上传: %s (%d 字节)", header.Filename, len(fileContent))
    })
    
    // 文件上传页面
    http.HandleFunc("/upload-page", func(w http.ResponseWriter, r *http.Request) {
        html := `
        <!DOCTYPE html>
        <html>
        <head>
            <title>文件上传</title>
            <meta charset="UTF-8">
        </head>
        <body>
            <h1>文件上传测试</h1>
            <form action="/upload" method="post" enctype="multipart/form-data">
                <input type="file" name="file" required>
                <button type="submit">上传文件</button>
            </form>
        </body>
        </html>
        `
        w.Header().Set("Content-Type", "text/html; charset=utf-8")
        fmt.Fprint(w, html)
    })
}

func main() {
    // 注册所有处理器
    httpMethodsHandler()
    userAPIHandlers()
    fileUploadHandler()
    
    // 应用中间件到特定路由
    http.HandleFunc("/api/protected", corsMiddleware(loggingMiddleware(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(map[string]string{
            "message": "这是受保护的端点",
            "status":  "success",
        })
    })))
    
    // 启动服务器
    fmt.Println("HTTP服务器启动在 http://localhost:8080")
    fmt.Println("可用端点:")
    fmt.Println("  GET  /")
    fmt.Println("  GET  /hello")
    fmt.Println("  GET  /time")
    fmt.Println("  *    /api/data")
    fmt.Println("  GET  /api/users")
    fmt.Println("  POST /api/users")
    fmt.Println("  GET  /api/users/{id}")
    fmt.Println("  PUT  /api/users/{id}")
    fmt.Println("  DELETE /api/users/{id}")
    fmt.Println("  GET  /upload-page")
    fmt.Println("  POST /upload")
    fmt.Println("  *    /api/protected")
    
    log.Fatal(http.ListenAndServe(":8080", nil))
}

HTTP客户端编程

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package main

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "io"
    "log"
    "net/http"
    "net/url"
    "strings"
    "time"
)

// 1. 基本HTTP客户端
func basicHTTPClient() {
    fmt.Println("=== 基本HTTP客户端 ===")
    
    // GET请求
    resp, err := http.Get("https://httpbin.org/get")
    if err != nil {
        log.Printf("GET请求失败: %v", err)
        return
    }
    defer resp.Body.Close()
    
    fmt.Printf("状态码: %d\n", resp.StatusCode)
    fmt.Printf("状态: %s\n", resp.Status)
    
    // 读取响应体
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Printf("读取响应体失败: %v", err)
        return
    }
    
    fmt.Printf("响应体长度: %d 字节\n", len(body))
    
    // 解析JSON响应
    var result map[string]interface{}
    if err := json.Unmarshal(body, &result); err == nil {
        if headers, ok := result["headers"].(map[string]interface{}); ok {
            fmt.Printf("User-Agent: %v\n", headers["User-Agent"])
        }
    }
}

// 2. POST请求和JSON数据
func postJSONData() {
    fmt.Println("\n=== POST JSON数据 ===")
    
    // 准备JSON数据
    data := map[string]interface{}{
        "name":  "测试用户",
        "email": "test@example.com",
        "age":   25,
    }
    
    jsonData, err := json.Marshal(data)
    if err != nil {
        log.Printf("JSON编码失败: %v", err)
        return
    }
    
    // 发送POST请求
    resp, err := http.Post("https://httpbin.org/post", 
        "application/json", bytes.NewBuffer(jsonData))
    if err != nil {
        log.Printf("POST请求失败: %v", err)
        return
    }
    defer resp.Body.Close()
    
    fmt.Printf("状态码: %d\n", resp.StatusCode)
    
    // 读取响应
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Printf("读取响应失败: %v", err)
        return
    }
    
    // 解析响应
    var result map[string]interface{}
    if err := json.Unmarshal(body, &result); err == nil {
        if jsonData, ok := result["json"].(map[string]interface{}); ok {
            fmt.Printf("服务器接收到的JSON: %+v\n", jsonData)
        }
    }
}

// 3. 表单数据提交
func postFormData() {
    fmt.Println("\n=== POST表单数据 ===")
    
    // 准备表单数据
    formData := url.Values{}
    formData.Set("username", "testuser")
    formData.Set("password", "testpass")
    formData.Set("email", "test@example.com")
    
    // 发送POST请求
    resp, err := http.PostForm("https://httpbin.org/post", formData)
    if err != nil {
        log.Printf("POST表单请求失败: %v", err)
        return
    }
    defer resp.Body.Close()
    
    fmt.Printf("状态码: %d\n", resp.StatusCode)
    
    // 读取响应
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Printf("读取响应失败: %v", err)
        return
    }
    
    // 解析响应
    var result map[string]interface{}
    if err := json.Unmarshal(body, &result); err == nil {
        if form, ok := result["form"].(map[string]interface{}); ok {
            fmt.Printf("服务器接收到的表单: %+v\n", form)
        }
    }
}

// 4. 自定义HTTP客户端
func customHTTPClient() {
    fmt.Println("\n=== 自定义HTTP客户端 ===")
    
    // 创建自定义客户端
    client := &http.Client{
        Timeout: 10 * time.Second,
        Transport: &http.Transport{
            MaxIdleConns:        10,
            IdleConnTimeout:     30 * time.Second,
            DisableCompression:  false,
        },
    }
    
    // 创建请求
    req, err := http.NewRequest("GET", "https://httpbin.org/delay/2", nil)
    if err != nil {
        log.Printf("创建请求失败: %v", err)
        return
    }
    
    // 设置请求头
    req.Header.Set("User-Agent", "Go-HTTP-Client/1.0")
    req.Header.Set("Accept", "application/json")
    req.Header.Set("Authorization", "Bearer token123")
    
    // 发送请求
    start := time.Now()
    resp, err := client.Do(req)
    if err != nil {
        log.Printf("请求失败: %v", err)
        return
    }
    defer resp.Body.Close()
    
    duration := time.Since(start)
    fmt.Printf("请求耗时: %v\n", duration)
    fmt.Printf("状态码: %d\n", resp.StatusCode)
    
    // 检查响应头
    fmt.Printf("Content-Type: %s\n", resp.Header.Get("Content-Type"))
    fmt.Printf("Content-Length: %s\n", resp.Header.Get("Content-Length"))
}

// 5. 带上下文的请求
func requestWithContext() {
    fmt.Println("\n=== 带上下文的请求 ===")
    
    // 创建带超时的上下文
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    
    // 创建请求
    req, err := http.NewRequestWithContext(ctx, "GET", 
        "https://httpbin.org/delay/5", nil)
    if err != nil {
        log.Printf("创建请求失败: %v", err)
        return
    }
    
    // 发送请求
    client := &http.Client{}
    start := time.Now()
    resp, err := client.Do(req)
    duration := time.Since(start)
    
    if err != nil {
        if ctx.Err() == context.DeadlineExceeded {
            fmt.Printf("请求超时 (耗时: %v)\n", duration)
        } else {
            log.Printf("请求失败: %v", err)
        }
        return
    }
    defer resp.Body.Close()
    
    fmt.Printf("请求成功 (耗时: %v)\n", duration)
    fmt.Printf("状态码: %d\n", resp.StatusCode)
}

// 6. 文件下载
func downloadFile() {
    fmt.Println("\n=== 文件下载 ===")
    
    // 下载文件
    resp, err := http.Get("https://httpbin.org/json")
    if err != nil {
        log.Printf("下载失败: %v", err)
        return
    }
    defer resp.Body.Close()
    
    if resp.StatusCode != http.StatusOK {
        log.Printf("下载失败,状态码: %d", resp.StatusCode)
        return
    }
    
    // 获取文件大小
    contentLength := resp.Header.Get("Content-Length")
    fmt.Printf("文件大小: %s 字节\n", contentLength)
    
    // 读取内容
    content, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Printf("读取内容失败: %v", err)
        return
    }
    
    fmt.Printf("下载完成,实际大小: %d 字节\n", len(content))
    
    // 如果是JSON,尝试解析
    var jsonData map[string]interface{}
    if err := json.Unmarshal(content, &jsonData); err == nil {
        fmt.Printf("JSON数据: %+v\n", jsonData)
    }
}

// 7. 并发HTTP请求
func concurrentRequests() {
    fmt.Println("\n=== 并发HTTP请求 ===")
    
    urls := []string{
        "https://httpbin.org/delay/1",
        "https://httpbin.org/delay/2",
        "https://httpbin.org/delay/1",
        "https://httpbin.org/status/200",
        "https://httpbin.org/json",
    }
    
    // 创建结果通道
    type Result struct {
        URL        string
        StatusCode int
        Duration   time.Duration
        Error      error
    }
    
    results := make(chan Result, len(urls))
    
    // 启动并发请求
    start := time.Now()
    for _, url := range urls {
        go func(u string) {
            reqStart := time.Now()
            resp, err := http.Get(u)
            duration := time.Since(reqStart)
            
            result := Result{
                URL:      u,
                Duration: duration,
                Error:    err,
            }
            
            if err == nil {
                result.StatusCode = resp.StatusCode
                resp.Body.Close()
            }
            
            results <- result
        }(url)
    }
    
    // 收集结果
    for i := 0; i < len(urls); i++ {
        result := <-results
        if result.Error != nil {
            fmt.Printf("请求失败: %s - %v (耗时: %v)\n", 
                result.URL, result.Error, result.Duration)
        } else {
            fmt.Printf("请求成功: %s - 状态码: %d (耗时: %v)\n", 
                result.URL, result.StatusCode, result.Duration)
        }
    }
    
    totalDuration := time.Since(start)
    fmt.Printf("总耗时: %v\n", totalDuration)
}

// 8. Cookie处理
func cookieHandling() {
    fmt.Println("\n=== Cookie处理 ===")
    
    // 创建带Cookie Jar的客户端
    jar := &http.CookieJar{}
    client := &http.Client{
        Jar: jar,
    }
    
    // 第一个请求 - 设置Cookie
    resp, err := client.Get("https://httpbin.org/cookies/set/session/abc123")
    if err != nil {
        log.Printf("设置Cookie失败: %v", err)
        return
    }
    resp.Body.Close()
    
    fmt.Printf("设置Cookie响应状态: %d\n", resp.StatusCode)
    
    // 第二个请求 - 使用Cookie
    resp, err = client.Get("https://httpbin.org/cookies")
    if err != nil {
        log.Printf("获取Cookie失败: %v", err)
        return
    }
    defer resp.Body.Close()
    
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Printf("读取响应失败: %v", err)
        return
    }
    
    var result map[string]interface{}
    if err := json.Unmarshal(body, &result); err == nil {
        if cookies, ok := result["cookies"].(map[string]interface{}); ok {
            fmt.Printf("服务器接收到的Cookie: %+v\n", cookies)
        }
    }
}

func main() {
    basicHTTPClient()
    postJSONData()
    postFormData()
    customHTTPClient()
    requestWithContext()
    downloadFile()
    concurrentRequests()
    cookieHandling()
}

总结

  1. HTTP服务器

    • http.HandleFunc() - 注册路由处理器
    • http.ListenAndServe() - 启动服务器
    • 支持不同HTTP方法处理
    • 中间件模式实现横切关注点
  2. HTTP客户端

    • http.Get() / http.Post() - 简单请求
    • http.Client - 自定义客户端配置
    • http.NewRequest() - 创建自定义请求
    • 支持超时、重试、Cookie等特性
  3. 数据处理

    • JSON编码解码
    • 表单数据处理
    • 文件上传下载
    • 请求响应头处理
  4. 高级特性

    • 中间件链
    • 上下文控制
    • 并发请求处理
    • Cookie和会话管理
  5. 最佳实践

    • 合理设置超时时间
    • 正确处理错误和状态码
    • 使用上下文控制请求生命周期
    • 实现适当的日志和监控
    • 注意资源清理和内存管理
updatedupdated2025-09-212025-09-21