-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
117 lines (96 loc) · 2.2 KB
/
main.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
114
115
116
package main
import (
"net/http"
"encoding/json"
"time"
"fmt"
"log"
"io"
"bytes"
"github.com/dandelion293949/todo/domains"
)
var (
repo = domains.New()
url = "/todos/"
)
func main() {
http.HandleFunc(url, handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func get(path string) []byte {
id := path[len(url):]
if id == "" {
todos, err := repo.GetAll()
if err != nil {
return []byte(`{ "error": "could not get todo"}`)
}
b, err := json.Marshal(todos)
if err != nil {
return []byte(`{ "error": "could not converted json"}`)
}
return b
} else {
todo, err := repo.Get(domains.TodoID(id))
if err != nil {
return []byte(`{ "error": "could not get todos"}`)
}
b, err := json.Marshal(*todo)
if err != nil {
return []byte(`{ "error": "could not converted json"}`)
}
return b
}
}
func create(todo domains.Todo) []byte {
t, err := repo.Create(&todo, time.Now())
if err != nil {
return []byte(`{ "error": "invalid request" }`)
}
b, err := json.Marshal(*t)
if err != nil {
return []byte(`{ "error": "could not converted json"}`)
}
return b
}
func update(todo domains.Todo) []byte {
t, err := repo.Update(&todo, time.Now())
if err != nil {
return []byte(`{ "error": "invalid request" }`)
}
b, err := json.Marshal(*t)
if err != nil {
return []byte(`{ "error": "could not converted json"}`)
}
return b
}
func delete(todo domains.Todo) []byte {
t, err := repo.Delete(&todo)
if err != nil {
return []byte(`{ "error": "invalid request" }`)
}
b, err := json.Marshal(*t)
if err != nil {
return []byte(`{ "error": "could not converted json"}`)
}
return b
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
fmt.Fprintf(w, "%s", get(r.URL.Path))
}
body := r.Body
defer body.Close()
buf := new(bytes.Buffer)
io.Copy(buf, body)
var todo domains.Todo
json.Unmarshal(buf.Bytes(), &todo)
if r.Method == http.MethodPost {
fmt.Fprintf(w, "%s", create(todo))
}
if r.Method == http.MethodPut {
fmt.Fprintf(w, "%s", update(todo))
}
if r.Method == http.MethodDelete {
fmt.Fprintf(w, "%s", delete(todo))
}
}