-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathroundtrip.go
219 lines (185 loc) · 5.02 KB
/
roundtrip.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"os"
"github.com/joyrexus/buckets"
mux "github.com/julienschmidt/httprouter"
)
const verbose = false // if `true` you'll see log output
func main() {
// Open a buckets database.
bx, err := buckets.Open(tempFilePath())
if err != nil {
log.Fatalf("couldn't open db: %v", err)
}
// Delete and close the db when done.
defer os.Remove(bx.Path())
defer bx.Close()
// Create a bucket for storing todos.
bucket, err := bx.New([]byte("todos"))
if err != nil {
log.Fatalf("couldn't create todos bucket: %v", err)
}
// Create our service for handling routes.
service := NewService(bucket)
// Create and setup our router.
router := mux.New()
router.GET("/:day", service.get)
router.POST("/:day", service.post)
// Start our web server.
srv := httptest.NewServer(router)
defer srv.Close()
// Daily todos for client to post.
posts := map[string]*Todo{
"/mon": {Day: "mon", Task: "milk cows"},
"/tue": {Day: "tue", Task: "fold laundry"},
"/wed": {Day: "wed", Task: "flip burgers"},
"/thu": {Day: "thu", Task: "join army"},
"/fri": {Day: "fri", Task: "kill time"},
"/sat": {Day: "sat", Task: "make merry"},
"/sun": {Day: "sun", Task: "pray quietly"},
}
// Create our client.
client := new(Client)
for path, todo := range posts {
url := srv.URL + path
if err := client.post(url, todo); err != nil {
fmt.Printf("client post error: %v", err)
}
}
for path := range posts {
url := srv.URL + path
task, err := client.get(url)
if err != nil {
fmt.Printf("client get error: %v", err)
}
fmt.Printf("%s: %s\n", path, task)
}
// Output:
// /mon: milk cows
// /tue: fold laundry
// /wed: flip burgers
// /thu: join army
// /fri: kill time
// /sat: make merry
// /sun: pray quietly
}
/* -- MODELS --*/
// Todo holds a task description and the day of week in which to do it.
type Todo struct {
Task string
Day string
}
// Encode marshals a Todo into a buffer.
func (todo *Todo) Encode() (*bytes.Buffer, error) {
b, err := json.Marshal(todo)
if err != nil {
return &bytes.Buffer{}, err
}
return bytes.NewBuffer(b), nil
}
/* -- SERVICE -- */
// NewService initializes a new instance of our service.
func NewService(bk *buckets.Bucket) *Service {
return &Service{bk}
}
// Service handles requests for todo items. The items are stored
// in a todos bucket. The request URLs are used as bucket keys and the
// raw json payload as values.
//
// In MVC parlance, our service would be called a "controller". We use
// it to define "handle" methods for our router. Note that since we're using
// `httprouter` (abbreviated as `mux` when imported) as our router, each
// service method is a `httprouter.Handle` rather than a `http.HandlerFunc`.
type Service struct {
todos *buckets.Bucket
}
// get handles get requests for a daily todo item.
func (s *Service) get(w http.ResponseWriter, r *http.Request, _ mux.Params) {
key := []byte(r.URL.String())
value, err := s.todos.Get(key)
if err != nil {
http.Error(w, err.Error(), 500)
}
w.Header().Set("Content-Type", "application/json")
w.Write(value)
}
// post handles post requests to create a daily todo item.
func (s *Service) post(w http.ResponseWriter, r *http.Request, _ mux.Params) {
// Read request body's json payload into buffer.
b, err := ioutil.ReadAll(r.Body)
todo, err := decode(b)
if err != nil {
http.Error(w, err.Error(), 500)
}
// Use the url path as key.
key := []byte(r.URL.String())
// Put key/buffer into todos bucket.
if err := s.todos.Put(key, b); err != nil {
http.Error(w, err.Error(), 500)
return
}
if verbose {
log.Printf("server: %s: %v", key, todo.Task)
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "put todo for %s: %s\n", key, todo)
}
/* -- CLIENT -- */
// Client is our http client for sending requests.
type Client struct{}
// post sends a post request with a json payload.
func (c *Client) post(url string, todo *Todo) error {
bodyType := "application/json"
body, err := todo.Encode()
if err != nil {
return err
}
resp, err := http.Post(url, bodyType, body)
if err != nil {
return err
}
if verbose {
log.Printf("client: %s\n", resp.Status)
}
return nil
}
// get sends get requests and expects responses to be a json-encoded todo item.
func (c *Client) get(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
todo := new(Todo)
if err = json.NewDecoder(resp.Body).Decode(todo); err != nil {
return "", err
}
return todo.Task, nil
}
/* -- UTILITY FUNCTIONS -- */
// decode unmarshals a json-encoded byteslice into a Todo.
func decode(b []byte) (*Todo, error) {
todo := new(Todo)
if err := json.Unmarshal(b, todo); err != nil {
return &Todo{}, err
}
return todo, nil
}
// tempFilePath returns a temporary file path.
func tempFilePath() string {
f, _ := ioutil.TempFile("", "bolt-")
if err := f.Close(); err != nil {
log.Fatal(err)
}
if err := os.Remove(f.Name()); err != nil {
log.Fatal(err)
}
return f.Name()
}