在Golang中,可以使用net/http包很容易地实现RESTful API。代码示例:
服务器:
go
func main() {
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
// GET /users
if r.Method == "GET" {
// 返回用户列表
w.Write([]byte(`[{"name": "user1"}, {"name": "user2"}]`))
}
// POST /users
if r.Method == "POST" {
// 添加新用户
w.WriteHeader(http.StatusCreated)
}
})
http.HandleFunc("/users/", func(w http.ResponseWriter, r *http.Request) {
// GET /users/1
if r.Method == "GET" {
// 返回用户信息
w.Write([]byte(`{"name": "user1"}`))
}
// PUT /users/1
if r.Method == "PUT" {
// 修改用户信息
w.WriteHeader(http.StatusOK)
}
// DELETE /users/1
if r.Method == "DELETE" {
// 删除用户
w.WriteHeader(http.StatusOK)
}
})
http.ListenAndServe(":8000", nil)
}
我们定义了两个路由,/users用于获取用户列表和添加新用户,/users/用于获取、修改和删除指定用户。通过判断HTTP Method来进行不同的操作。
客户端:
go
// GET /users
resp, err := http.Get("http://localhost:8000/users")
if err != nil {
log.Fatal(err)
}
// POST /users
req, err := http.NewRequest("POST", "http://localhost:8000/users", nil)
if err != nil {
log.Fatal(err)
}
client := &http.Client{}
resp, err = client.Do(req)
// GET /users/1
resp, err = http.Get("http://localhost:8000/users/1")
// PUT /users/1
req, err = http.NewRequest("PUT", "http://localhost:8000/users/1", nil)
resp, err = client.Do(req)
// DELETE /users/1
req, err = http.NewRequest("DELETE", "http://localhost:8000/users/1", nil)
resp, err = client.Do(req)
客户端通过不同的HTTP Method向服务器发送请求,实现用户的获取、添加、修改和删除等操作。