Go实现简单的RESTful_API
Go实现简单的RESTful_API何为RESTful APIA 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 w...
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 main
import (
"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 function
router.HandleFunc("/people/{id}", PostPerson).Methods("POST")
// Delete handle function:
router.HandleFunc("/people/{id}", DeletePerson).Methods("DELETE")
// 启动 API端口9899
log.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"}
}
]
更多推荐
所有评论(0)