-
Notifications
You must be signed in to change notification settings - Fork 2k
/
server.go
113 lines (104 loc) · 2.07 KB
/
server.go
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
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"encoding/json"
"net/http"
"path"
"strconv"
)
func main() {
http.HandleFunc("/topic/", handleRequest)
http.ListenAndServe(":2017", nil)
}
// main handler function
func handleRequest(w http.ResponseWriter, r *http.Request) {
var err error
switch r.Method {
case http.MethodGet:
err = handleGet(w, r)
case http.MethodPost:
err = handlePost(w, r)
case http.MethodPut:
err = handlePut(w, r)
case http.MethodDelete:
err = handleDelete(w, r)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// 获取一个帖子
// 如 GET /topic/1
func handleGet(w http.ResponseWriter, r *http.Request) error {
id, err := strconv.Atoi(path.Base(r.URL.Path))
if err != nil {
return err
}
topic, err := FindTopic(id)
if err != nil {
return err
}
output, err := json.MarshalIndent(&topic, "", "\t\t")
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
w.Write(output)
return nil
}
// 增加一个帖子
// POST /topic/
func handlePost(w http.ResponseWriter, r *http.Request) (err error) {
body := make([]byte, r.ContentLength)
r.Body.Read(body)
var topic = new(Topic)
err = json.Unmarshal(body, &topic)
if err != nil {
return
}
err = topic.Create()
if err != nil {
return
}
w.WriteHeader(http.StatusOK)
return
}
// 更新一个帖子
// PUT /topic/1
func handlePut(w http.ResponseWriter, r *http.Request) error {
id, err := strconv.Atoi(path.Base(r.URL.Path))
if err != nil {
return err
}
topic, err := FindTopic(id)
if err != nil {
return err
}
body := make([]byte, r.ContentLength)
r.Body.Read(body)
json.Unmarshal(body, topic)
err = topic.Update()
if err != nil {
return err
}
w.WriteHeader(http.StatusOK)
return nil
}
// 删除一个帖子
// DELETE /topic/1
func handleDelete(w http.ResponseWriter, r *http.Request) (err error) {
id, err := strconv.Atoi(path.Base(r.URL.Path))
if err != nil {
return
}
topic, err := FindTopic(id)
if err != nil {
return
}
err = topic.Delete()
if err != nil {
return
}
w.WriteHeader(http.StatusOK)
return
}