-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.go
358 lines (311 loc) · 9.32 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
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package main
// The import section defines libraries that we are going to use in our program.
import (
"fmt"
"log"
"net/http"
"crypto/rand"
"encoding/json"
"github.com/gorilla/mux"
"github.com/ory-am/common/env"
"github.com/ory-am/common/pkg"
"github.com/pborman/uuid"
"github.com/rs/cors"
"math"
"strconv"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
. "github.com/ory/workshop-dbg/store"
"github.com/ory/workshop-dbg/store/memory"
"github.com/ory/workshop-dbg/store/postgres"
"time"
)
// In a 12 factor app, we must obey the environment variables.
var envHost = env.Getenv("HOST", "")
var envPort = env.Getenv("PORT", "5678")
var databaseURL = env.Getenv("DATABASE_URL", "")
var thisID = uuid.New()
// MyContacts is an exemplary list of contacts.
var MyContacts = Contacts{
// Each contact hs identified by its ID which is prepended with "my-id":
// We are doing this because it is easier to manage and simpler to read.
"john-bravo": &Contact{
Name: "Andreas Preuss",
Department: "IT",
Company: "ACME Inc",
},
"cathrine-mueller": &Contact{
Name: "Cathrine Eholzer",
Department: "HR",
Company: "Grove AG",
},
"maximilian-schmidt": &Contact{
Name: "Maximilian Schmidt",
Department: "PR",
Company: "Titanpad AG",
},
"uwe-charly": &Contact{
Name: "Uwe Charly",
Department: "FAC",
Company: "KPMG",
},
"Thomas-Aidan": &Contact{
Name: "Thomas Aigan",
Department: "INO",
Company: "OuterSpace",
},
"frank-sec": &Contact{
Name: "Frank Secure",
Department: "Unknow",
Company: "Secret",
},
"juergen-elsner": &Contact{
Name: "Jürgen Elsner",
Department: "DaCS",
Company: "DBG",
},
"Stephane-Deschamps": &Contact{
Name: "Stephane Deschamps",
Department: "DaCS",
Company: "DBG",
},
"Gilles-Lamy": &Contact{
Name: "MGilles Lamy",
Department: "DaCS",
Company: "DBG",
},
"Helge Harren": &Contact{
Name: "Helge Harren",
Department: "TRIT",
Company: "DBG",
},
"Stephan Reinartz": &Contact{
Name: "Stephan Reinartz",
Department: "SMMI",
Company: "DBG",
},
"Ulrich Meyer": &Contact{
Name: "Ulrich Meyer",
Department: "TRIT",
Company: "DBG",
},
"Ashwin Kumar": &Contact{
Name: "Ashwin Kumar",
Department: "GPD",
Company: "DBG",
},
"Stefan Teis": &Contact{
Name: "Stefan Teis",
Department: "GPD",
Company: "DBG",
},
}
var memoryStore = &memory.InMemoryStore{Contacts: MyContacts}
// The main routine is going the "entry" point.
func main() {
// Create a new router.
router := mux.NewRouter()
// RESTful defines operations
// * GET for fetching data
// * POST for inserting data
// * PUT for updating existing data
// * DELETE for deleting data
router.HandleFunc("/memory/contacts", ListContacts(memoryStore)).Methods("GET")
router.HandleFunc("/memory/contacts", AddContact(memoryStore)).Methods("POST")
router.HandleFunc("/memory/contacts/{id}", UpdateContact(memoryStore)).Methods("PUT")
router.HandleFunc("/memory/contacts/{id}", DeleteContact(memoryStore)).Methods("DELETE")
// Connect to database store
db, err := sqlx.Connect("postgres", databaseURL)
if err != nil {
log.Printf("Could not connect to database because %s", err)
} else {
databaseStore := &postgres.PostgresStore{DB: db}
if err := databaseStore.CreateSchemas(); err != nil {
log.Printf("Could not set up relations %s", err)
} else {
router.HandleFunc("/database/contacts", ListContacts(databaseStore)).Methods("GET")
router.HandleFunc("/database/contacts", AddContact(databaseStore)).Methods("POST")
router.HandleFunc("/database/contacts/{id}", UpdateContact(databaseStore)).Methods("PUT")
router.HandleFunc("/database/contacts/{id}", DeleteContact(databaseStore)).Methods("DELETE")
}
}
// The info endpoint is for showing demonstration purposes only and is not subject to any task.
router.HandleFunc("/info", InfoHandler).Methods("GET")
router.HandleFunc("/pi", ComputePi).Methods("GET")
router.HandleFunc("/pis", ComputePis).Methods("GET")
router.HandleFunc("/allocate", Allocate).Methods("GET")
// Print where to point the browser at.
fmt.Printf("Listening on %s\n", "http://localhost:5678")
// Cross origin resource requests
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "DELETE", "PUT"}},
)
// Start up the server and check for errors.
listenOn := fmt.Sprintf("%s:%s", envHost, envPort)
if err := http.ListenAndServe(listenOn, c.Handler(router)); err != nil {
log.Fatalf("Could not set up server because %s", err)
}
}
// ListContacts takes a contact list and outputs it.
func ListContacts(store ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
// Write contact list to output
contacts, err := store.FetchContacts()
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
pkg.WriteIndentJSON(rw, contacts)
}
}
// ContactsMeta gets the metadata.
func ContactsMeta (rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type","application/json")
}
// AddContact will add a contact to the list
func AddContact(contacts ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
// We parse the request's information into contactToBeAdded
contactToBeAdded, err := ReadContactData(rw, r)
// Abort handling the request if an error occurs.
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
// Save newContact to the list of contacts.
if err = contacts.CreateContact(&contactToBeAdded); err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
// Output our newly created contact
pkg.WriteIndentJSON(rw, contactToBeAdded)
}
}
// DeleteContact will delete a contact from the list
func DeleteContact(contacts ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
// Fetch the ID of the contact that is going to be deleted
contactToBeDeleted := mux.Vars(r)["id"]
// Delete the contact from the list
if err := contacts.DeleteContact(contactToBeDeleted); err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
// Per specification, RESTful may return an empty response when a DELETE request was successful
rw.WriteHeader(http.StatusNoContent)
}
}
// UpdateContact will update a contact on the list
func UpdateContact(store ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
// We parse the request's information into newContactData.
newContactData, err := ReadContactData(rw, r)
// Abort handling the request if an error occurs.
if err != nil {
http.Error(rw, err.Error(), http.StatusBadRequest)
return
}
// Update the data in the contact list.
if err := store.UpdateContact(&newContactData); err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
// Set the new data
pkg.WriteIndentJSON(rw, newContactData)
}
}
// ReadContactData is a helper function for parsing a HTTP request body. It returns a contact on success and an
// error if something went wrong.
func ReadContactData(rw http.ResponseWriter, r *http.Request) (contact Contact, err error) {
err = json.NewDecoder(r.Body).Decode(&contact)
if err != nil {
http.Error(rw, fmt.Sprintf("Could not read input data because %s", err), http.StatusBadRequest)
return contact, err
}
return contact, nil
}
func Allocate(rw http.ResponseWriter, r *http.Request) {
n, err := strconv.Atoi(r.URL.Query().Get("n"))
if err != nil {
n = 0
}
t, err := strconv.Atoi(r.URL.Query().Get("t"))
if err != nil {
t = 5
}
m := make([][]byte, n + 1)
for i := 0; i < n; i++ {
z := make([]byte, n + 1)
_, _ = rand.Read(z)
m[i] = z
}
time.Sleep(time.Second * time.Duration(t))
pkg.WriteIndentJSON(rw, struct {
Result string `json:"result"`
N int `json:"n"`
}{
Result: "Processed!",
N: n,
})
}
func ComputePi(rw http.ResponseWriter, r *http.Request) {
n, err := strconv.Atoi(r.URL.Query().Get("n"))
if err != nil {
n = 0
}
pkg.WriteIndentJSON(rw, struct {
Pi string `json:"pi"`
N int `json:"n"`
}{
Pi: strconv.FormatFloat(pi(n), 'E', -1, 64),
N: n,
})
}
func ComputePis(rw http.ResponseWriter, r *http.Request) {
n, err := strconv.Atoi(r.URL.Query().Get("n"))
if err != nil {
n = 0
}
pkg.WriteIndentJSON(rw, struct {
Pi string `json:"pi"`
N int `json:"n"`
}{
Pi: strconv.FormatFloat(pis(int64(n)), 'E', -1, 64),
N: n,
})
}
func InfoHandler(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte(thisID))
}
// pi launches n goroutines to compute an
// approximation of pi.
func pis(n int64) float64 {
f := 0.0
k := 0.0
start := time.Now()
for start.Add(time.Second * time.Duration(n)).After(time.Now()) {
f += terms(k)
k++
}
return f
}
func terms(k float64) float64 {
return 4 * math.Pow(-1, k) / (2 * k + 1)
}
// pi launches n goroutines to compute an
// approximation of pi.
func pi(n int) float64 {
ch := make(chan float64)
for k := 0; k <= n; k++ {
go term(ch, float64(k))
}
f := 0.0
for k := 0; k <= n; k++ {
f += <-ch
}
return f
}
func term(ch chan float64, k float64) {
ch <- 4 * math.Pow(-1, k) / (2 * k + 1)
}