日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Go实现简单的RESTful_API

發(fā)布時間:2025/3/8 编程问答 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Go实现简单的RESTful_API 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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年在他的博士論文中提出來的一種軟件架構(gòu)風格。
Roy Fielding是HTTP協(xié)議(1.0版和1.1版)的主要設計者,事實上HTTP 1.1規(guī)范正是基于REST架構(gòu)風格的指導原理來設計的。需要注意的是,REST是一種設計風格而不是標準,如果一個架構(gòu)符合REST原則,我們就稱它為RESTful架構(gòu)。

gorilla/mux

golang自帶的http.SeverMux路由實現(xiàn)簡單,本質(zhì)是一個map[string]Handler,是請求路徑與該路徑對應的處理函數(shù)的映射關系。實現(xiàn)簡單功能也比較單一:

  • 不支持正則路由, 這個是比較致命的
  • 只支持路徑匹配,不支持按照Method,header,host等信息匹配,所以也就沒法實現(xiàn)RESTful架構(gòu)
  • 安裝第三方安裝包

    go get -u github.com/gorilla/mux

    實現(xiàn)

  • 定義結(jié)構(gòu)體,用戶構(gòu)造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"` }
  • 接下來,定義一個全局變量,用于存儲資源(數(shù)據(jù)):
  • var people []Person
  • Get
  • 獲取所有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
  • 同樣可以,通過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
  • 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) } // 根據(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"}} ]

    總結(jié)

    以上是生活随笔為你收集整理的Go实现简单的RESTful_API的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。