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
|
// 用户结构体
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
// 模拟数据库
var users = map[string]User{
"1": {ID: "1", Name: "张三", Age: 30},
"2": {ID: "2", Name: "李四", Age: 25},
}
func main() {
// 使用ServeMux路由
mux := http.NewServeMux()
// 注册路由
mux.HandleFunc("/users", getUsers)
mux.HandleFunc("/users/", getUser)
mux.HandleFunc("/users/create", createUser)
mux.HandleFunc("/users/update/", updateUser)
mux.HandleFunc("/users/delete/", deleteUser)
// 添加CORS中间件
handler := corsMiddleware(mux)
// 启动服务器
fmt.Println("REST API服务器启动,监听端口 8080...")
http.ListenAndServe(":8080", handler)
}
// 获取所有用户
func getUsers(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
// 获取单个用户
func getUser(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
// 提取用户ID
id := strings.TrimPrefix(r.URL.Path, "/users/")
if id == "" {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "缺少用户ID"})
return
}
user, exists := users[id]
if !exists {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]string{"error": "用户不存在"})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
// 创建用户
func createUser(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var newUser User
if err := json.NewDecoder(r.Body).Decode(&newUser); err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "无效的用户数据"})
return
}
// 简单生成ID
newID := fmt.Sprintf("%d", len(users)+1)
newUser.ID = newID
users[newID] = newUser
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(newUser)
}
// 更新用户
func updateUser(w http.ResponseWriter, r *http.Request) {
if r.Method != "PUT" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
id := strings.TrimPrefix(r.URL.Path, "/users/update/")
if id == "" {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "缺少用户ID"})
return
}
if _, exists := users[id]; !exists {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]string{"error": "用户不存在"})
return
}
var updatedUser User
if err := json.NewDecoder(r.Body).Decode(&updatedUser); err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "无效的用户数据"})
return
}
updatedUser.ID = id
users[id] = updatedUser
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(updatedUser)
}
// 删除用户
func deleteUser(w http.ResponseWriter, r *http.Request) {
if r.Method != "DELETE" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
id := strings.TrimPrefix(r.URL.Path, "/users/delete/")
if id == "" {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "缺少用户ID"})
return
}
if _, exists := users[id]; !exists {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]string{"error": "用户不存在"})
return
}
delete(users, id)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "用户删除成功"})
}
// CORS中间件
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
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 == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
|