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))
}
|