-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandlers.go
78 lines (65 loc) · 1.87 KB
/
handlers.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
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"github.com/julienschmidt/httprouter"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprintf(w, "Welcmoe!")
}
func YamaIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(yamas); err != nil {
panic(err)
}
}
func YamaShow(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
id, _ := strconv.Atoi(ps.ByName("yamaId"))
t := RepoFindYama(id)
if t.ID == 0 && t.Proposer == "" {
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(t); err != nil {
panic(err)
}
}
func YamaCreate(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
var yama Yama
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576)) // 1MiB
if err != nil {
panic(err)
}
defer r.Body.Close()
if err := json.Unmarshal(body, &yama); err != nil {
w.WriteHeader(500)
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
return
}
t := RepoCreateYama(yama)
location := fmt.Sprintf("http://%s/%d", r.Host, t.ID)
w.Header().Set("Location", location)
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(t); err != nil {
panic(err)
}
}
func YamaDelete(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
id, _ := strconv.Atoi(ps.ByName("yamaId"))
if err := RepoDestroyYama(id); err != nil {
w.WriteHeader(http.StatusNotFound)
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
return
}
w.Header().Del("Content-Type")
w.WriteHeader(204) // 204 No Content
}