Go實現簡單的RESTful_API
何為RESTful API
A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data.
A RESTful API – also referred to as a RESTful web service – is based on representational state transfer (REST) technology, an architectural style and approach to communications often used in web services development.
Wikipedia: 表征性狀態傳輸(英文:Representational State Transfer,簡稱REST)是Roy Fielding博士于2000年在他的博士論文中提出來的一種軟件架構風格。
Roy Fielding是HTTP協議(1.0版和1.1版)的主要設計者,事實上HTTP 1.1規范正是基于REST架構風格的指導原理來設計的。需要注意的是,REST是一種設計風格而不是標準,如果一個架構符合REST原則,我們就稱它為RESTful架構。
gorilla/mux
golang自帶的http.SeverMux路由實現簡單,本質是一個map[string]Handler,是請求路徑與該路徑對應的處理函數的映射關系。實現簡單功能也比較單一:
- 不支持正則路由, 這個是比較致命的
- 只支持路徑匹配,不支持按照Method,header,host等信息匹配,所以也就沒法實現RESTful架構
安裝第三方安裝包
go get -u github.com/gorilla/mux
實現
- 定義結構體,用戶構造json
type Person struct {ID string `json:"id,omitemty"`Firstname string `json:"firstname,omitempty"`Lastname string `json:"lastname,omitempty"`Address *Address `json:"address,omitempty"`
}type Address struct {City string `json:"city,omitempty"`Province string `json:"province,omitempty"`
}
- 接下來,定義一個全局變量,用于存儲資源(數據):
var people []Person
- Get
獲取所有person,這里我們叫people:
func GetPeople(w http.ResponseWriter, req *http.Request) {json.NewEncoder(w).Encode(people)
}
根據id獲取person:
func GetPerson(w http.ResponseWriter, req *http.Request) {params := mux.Vars(req)for _, item := range people {if item.ID == params["id"] {json.NewEncoder(w).Encode(item)return}}json.NewEncoder(w).Encode(people)
}
- post
同樣可以,通過post操作向服務器添加數據:
func PostPerson(w http.ResponseWriter, req *http.Request) {params := mux.Vars(req)var person Person_ = json.NewDecoder(req.Body).Decode(&person)person.ID = params["id"]people = append(people, person)json.NewEncoder(w).Encode(people)
}
- Delete
func DeletePerson(w http.ResponseWriter, req *http.Request) {params := mux.Vars(req)for index, item := range people {if item.ID == params["id"] {people = append(people[:index], people[index+1:]...)break}}json.NewEncoder(w).Encode(people)
}
完整代碼
package mainimport ("encoding/json""log""net/http""github.com/gorilla/mux"
)type Person struct {ID string `json:"id,omitemty"`Firstname string `json:"firstname,omitempty"`Lastname string `json:"lastname,omitempty"`Address *Address `json:"address,omitempty"`
}type Address struct {City string `json:"city,omitempty"`Province string `json:"province,omitempty"`
}var people []Person
// *******************************************************************>>
// Get
// 獲取所有person
func GetPeople(w http.ResponseWriter, req *http.Request) {json.NewEncoder(w).Encode(people)
}
// 根據id獲取person
func GetPerson(w http.ResponseWriter, req *http.Request) {params := mux.Vars(req)for _, item := range people {if item.ID == params["id"] {json.NewEncoder(w).Encode(item)return}}json.NewEncoder(w).Encode(people)
}
// <<*******************************************************************
// *******************************************************************>>
// Post
// 通過post操作向服務器添加數據
func PostPerson(w http.ResponseWriter, req *http.Request) {params := mux.Vars(req)var person Person_ = json.NewDecoder(req.Body).Decode(&person)person.ID = params["id"]people = append(people, person)json.NewEncoder(w).Encode(people)
}
// <<*******************************************************************
// *******************************************************************>>
// Delete
// 根據id進行刪除操作
func DeletePerson(w http.ResponseWriter, req *http.Request) {params := mux.Vars(req)for index, item := range people {if item.ID == params["id"] {people = append(people[:index], people[index+1:]...)break}}json.NewEncoder(w).Encode(people)
}
// <<*******************************************************************func main() {people = append(people, Person{ID: "1", Firstname: "xi", Lastname: "dada", Address: &Address{City: "Shenyang", Province: "Liaoning"}})people = append(people, Person{ID: "2", Firstname: "li", Lastname: "xiansheng", Address: &Address{City: "Changchun", Province: "Jinlin"}}) // Get handle function:router := mux.NewRouter()router.HandleFunc("/people", GetPeople).Methods("GET")router.HandleFunc("/people/{id}", GetPerson).Methods("GET") // Post handle functionrouter.HandleFunc("/people/{id}", PostPerson).Methods("POST") // Delete handle function:router.HandleFunc("/people/{id}", DeletePerson).Methods("DELETE") // 啟動 API端口9899log.Fatal(http.ListenAndServe(":9899", router))
}
運行:
go run ***.go
或者編譯成二進制運行
go build ***.go
然后在瀏覽器中測試
http://localhost:9899/people
[{"id":"1","firstname":"xi","lastname":"dada","address":{"city":"Shenyang","province":"Liaoning"}},{"id":"2","firstname":"li","lastname":"xiansheng","address":{"city":"Changchun","province":"Jinlin"}}
]