-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (94 loc) · 2.18 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
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"path/filepath"
"time"
"github.com/labstack/echo/v4"
)
var (
Commit = "HEAD"
)
func main() {
upSince := time.Now()
dataPath := "."
// read the CSV file
// use FAKESTOCK_PATH environment variable to override the default if present
if os.Getenv("FAKESTOCK_PATH") != "" {
dataPath = os.Getenv("FAKESTOCK_PATH")
}
tickers := make(map[string]*Ticker)
startPricesFile := filepath.Join(dataPath, "nasdaq.csv")
err := LoadStartPrices(startPricesFile, NASDAQ, tickers)
if err != nil {
panic(err)
}
startPricesFile = filepath.Join(dataPath, "nyse.csv")
err = LoadStartPrices(startPricesFile, NYSE, tickers)
if err != nil {
panic(err)
}
fmt.Printf("Loaded %d tickers\n", len(tickers))
quit := make(chan struct{})
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for _ = range c {
fmt.Println("\nReceived an interrupt, stopping services...")
quit <- struct{}{}
}
}()
e := echo.New()
e.GET("/tickers", func(c echo.Context) error {
// return all tickers
return c.JSON(http.StatusOK, tickers)
})
e.GET("/tickers/:symbol", func(c echo.Context) error {
// return ticker for the given symbol
symbol := c.Param("symbol")
ticker, ok := tickers[symbol]
if !ok {
return c.JSON(http.StatusNotFound, "Ticker not found")
}
return c.JSON(http.StatusOK, ticker)
})
e.GET("/exchanges", func(c echo.Context) error {
// return all exchanges
return c.JSON(http.StatusOK, map[string]interface{}{
"NYSE": NYSE,
"NASDAQ": NASDAQ,
})
})
e.GET("/_ping", func(c echo.Context) error {
// return the current commit hash
return c.JSON(http.StatusOK, map[string]interface{}{
"commit": Commit,
"uptime": time.Since(upSince).String(),
})
})
go func() {
e.Logger.Fatal(e.Start("0.0.0.0:8080"))
}()
ticker := time.NewTicker(5 * time.Second)
go func() {
for {
select {
case <-ticker.C:
for _, ticker := range tickers {
ticker.UpdatePrice()
}
}
}
}()
<-quit
ticker.Stop()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := e.Shutdown(ctx); err != nil {
e.Logger.Fatal(err)
}
return
}