0%

REST api简单应用(未完成)

在初步了解REST的概念后,博主决定写一个简单的REST api应用来加深自己对REST的印象

目的

开发一个api,实现动物园与动物的信息:

http://api.example.com/zoos
http://api.example.com/animals

资源的具体操作:

GET /zoos:列出所有动物园
POST /zoos:新建一个动物园
GET /zoos/ID:获取某个指定动物园的信息
PUT /zoos/ID:更新某个指定动物园的信息(提供该动物园的全部信息)
PATCH /zoos/ID:更新某个指定动物园的信息(提供该动物园的部分信息)
DELETE /zoos/ID:删除某个动物园
GET /zoos/ID/animals:列出某个指定动物园的所有动物
DELETE /zoos/ID/animals/ID:删除某个指定动物园的指定动物

过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//main.go
package main

import (
"encoding/json"
"fmt"
"log"
"net/http"
"rest_api/structs"

"github.com/julienschmidt/httprouter"
)

var zoos map[string]structs.Zoo

func zoosGet(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, zooJson(zoos))
}

func zoosPost(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
zid := r.FormValue("zid")
zname := r.FormValue("zname")
if _, ok := zoos[zid]; ok {
fmt.Fprintf(w, `{error: "zoo is exists!"}`)
return
} else {
zoos[zid] = structs.Zoo{zid, zname, []structs.Animal{}}
fmt.Fprintf(w, zooJson(zoos[zid]))
}
}

func zooGet(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
zid := ps.ByName("zid")
if zoo, ok := zoos[zid]; ok {
fmt.Fprintf(w, zooJson(zoo))
} else {
fmt.Fprintf(w, `{error: "zoo is not exists!"}`)
}
}

func zooDel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
zid := ps.ByName("zid")
if _, ok := zoos[zid]; ok {
delete(zoos, zid)
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusNotFound)
}
}

func zooPut(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
zid := r.FormValue("zid")
zname := r.FormValue("zname")

if _, ok := zoos[zid]; ok {
zoos[zid] = structs.Zoo{zid, zname, []structs.Animal{}}
fmt.Fprintf(w, zooJson(zoos[zid]))
return
} else {
fmt.Fprintf(w, `{error: "zoo is not exists!"}`)
return
}

}

func main() {
zoos = make(map[string]structs.Zoo)
zoos["001"] = structs.Zoo{"001", "zoo1", []structs.Animal{{"001", "dog"}, {"002", "cat"}}}

router := httprouter.New()
router.GET("/zoos", zoosGet)
router.POST("/zoos", zoosPost)
router.GET("/zoos/:zid", zooGet)
router.DELETE("/zoo/:zid", zooDel)
router.PUT("/zoo/:zid", zooPut)
if err := http.ListenAndServe(":8080", router); err != nil {
log.Fatal(err)
}
}

func zooJson(zoos interface{}) string {
jsonData, err := json.Marshal(zoos)
if err != nil {
log.Fatal(err)
}
return string(jsonData)
}

//structs.go
package structs

type Zoo struct{
Id string
Name string
Animals []Animal
}

type Animal struct{
Id string
Name string
}

结语

这个REST api应用简单的实现了REST架构,不过由于处于本菜鸟之手,许多地方尚需完善,还待以后慢慢补正~

参考文档: 阮一峰:RESTful API设计指南