Go实现简单的RESTful_API
Go實現(xiàn)簡單的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: 表征性狀態(tài)傳輸(英文:Representational State Transfer,簡稱REST)是Roy Fielding博士于2000年在他的博士論文中提出來的一種軟件架構風格。
Roy Fielding是HTTP協(xié)議(1.0版和1.1版)的主要設計者,事實上HTTP 1.1規(guī)范正是基于REST架構風格的指導原理來設計的。需要注意的是,REST是一種設計風格而不是標準,如果一個架構符合REST原則,我們就稱它為RESTful架構。
gorilla/mux
golang自帶的http.SeverMux路由實現(xiàn)簡單,本質是一個map[string]Handler,是請求路徑與該路徑對應的處理函數(shù)的映射關系。實現(xiàn)簡單功能也比較單一:
安裝第三方安裝包
go get -u github.com/gorilla/mux實現(xiàn)
獲取所有person,這里我們叫people:
func GetPeople(w http.ResponseWriter, req *http.Request) {json.NewEncoder(w).Encode(people) }根據(jù)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操作向服務器添加數(shù)據(jù):
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) }完整代碼
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) } // 根據(jù)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操作向服務器添加數(shù)據(jù) 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 // 根據(jù)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"}} ]總結
以上是生活随笔為你收集整理的Go实现简单的RESTful_API的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 采用递归求第n位数【C#】
- 下一篇: UVA1025——A Spy in th