forked from libreoscar/ethmarket_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
84 lines (68 loc) · 1.54 KB
/
main.go
File metadata and controls
84 lines (68 loc) · 1.54 KB
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
package main
import (
"encoding/json"
"math/rand"
"strconv"
"time"
"github.com/hoisie/web"
"github.com/libreoscar/ethmarket_interview/orders"
"github.com/libreoscar/utils/log"
)
var (
logger = log.New(log.DEBUG)
)
func init() {
rand.Seed(1234)
}
func randSide() string {
r := rand.Intn(2)
if r == 0 {
return "ask"
}
return "bid"
}
func generateOrders(pump *orders.OrderPump) {
for {
durMs := 200 + 2*rand.Intn(1000)
time.Sleep(time.Duration(durMs) * time.Millisecond)
order := &orders.Order{
Side: randSide(),
Quantity: 1 + rand.Intn(15),
Price: 50.0 + float64(rand.Intn(180)),
}
pump.AddOrder(order)
}
}
func listOrders(ctx *web.Context, pump *orders.OrderPump) {
start, err := strconv.Atoi(ctx.Params["start"])
if err != nil || start < 0 {
ctx.ResponseWriter.WriteHeader(400)
ctx.ResponseWriter.Write([]byte(`Invalid values for param "start"`))
return
}
size, err := strconv.Atoi(ctx.Params["size"])
if err != nil || size < 0 {
ctx.ResponseWriter.WriteHeader(400)
ctx.ResponseWriter.Write([]byte(`Invalid values for param "size"`))
return
}
orders := pump.List(start, size)
ctx.ContentType("json")
err = json.NewEncoder(ctx).Encode(orders)
if err != nil {
panic(err)
}
}
func main() {
pump := orders.NewOrderPump()
go generateOrders(pump)
web.Get("/reset", func(ctx *web.Context) {
logger.Debug("Handling Get /reset")
pump.Clear()
})
web.Get("/listOrders", func(ctx *web.Context) {
logger.Debug("Handling Get /listOrders")
listOrders(ctx, pump)
})
web.Run("0.0.0.0:9888")
}