-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathhandlers.go
221 lines (192 loc) · 7.07 KB
/
handlers.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
package main
import (
"context"
"encoding/json"
"net/http"
"github.com/go-chi/chi/v5"
)
// portfolioTpl is used to represent the data which is used to render
// portfolio web view.
type portfolioTpl struct {
DailyPortfolioReturns []DailyReturns `json:"daily_portfolio_returns"`
DailyIndexReturns []DailyReturns `json:"daily_index_returns"`
AvgStockReturns AvgStockReturns `json:"avg_stock_returns"`
AvgIndexReturns map[int]float64 `json:"avg_index_returns"`
AvgPortfolioReturns map[int]float64 `json:"avg_portfolio_returns"`
CurrentPortfolioAmount int64 `json:"current_portfolio_amount"`
CurrentIndexAmount int64 `json:"curent_index_amount"`
ShareID string `json:"uuid"`
Category string `json:"category"`
}
// wrap is a middleware that wraps HTTP handlers and injects the "app" context.
func wrap(app *App, next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "app", app)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// resp is used to send uniform response structure.
type resp struct {
Status string `json:"status"`
Message string `json:"message,omitempty"`
Data interface{} `json:"data,omitempty"`
}
// sendResponse sends a JSON envelope to the HTTP response.
func sendResponse(w http.ResponseWriter, code int, data interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
out, err := json.Marshal(resp{Status: "success", Data: data})
if err != nil {
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
w.Write(out)
}
// sendErrorResponse sends a JSON error envelope to the HTTP response.
func sendErrorResponse(w http.ResponseWriter, message string, code int, data interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
resp := resp{
Status: "error",
Message: message,
Data: data,
}
// TODO: Have an error.html?
out, err := json.Marshal(resp)
if err != nil {
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
w.Write(out)
}
// handleIndex serves the index page.
func handleIndex(w http.ResponseWriter, r *http.Request) {
var (
app = r.Context().Value("app").(*App)
)
if err := app.tpl.ExecuteTemplate(w, "index", nil); err != nil {
app.lo.Error("error rendering template", "error", err)
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
}
// handlePortfolio serves the portfolio page.
func handlePortfolio(w http.ResponseWriter, r *http.Request) {
var (
app = r.Context().Value("app").(*App)
portfolio = make(ReturnsPeriod, 0)
index = make(ReturnsPeriod, 0)
avgStockReturns = make(AvgStockReturns, 0)
avgPortfolioReturns = make(map[int]float64, 0)
avgIndexReturns = make(map[int]float64, 0)
dailyPortfolioReturns = make([]DailyReturns, 0)
dailyIndexReturns = make([]DailyReturns, 0)
)
// Check if UUID is in URL.
uuid := chi.URLParam(r, "uuid")
if uuid != "" {
// If it exists, then simply lookup the data for the given UUID and render HTML.
portfolioTpl, err := app.getLink(uuid)
if err != nil {
app.lo.Error("error fetching data for uuid", "error", err, "uuid", uuid)
sendErrorResponse(w, "Invalid UUID", http.StatusBadRequest, nil)
return
}
// Set the UUID in the template.
portfolioTpl.ShareID = uuid
if err := app.tpl.ExecuteTemplate(w, "portfolio", portfolioTpl); err != nil {
app.lo.Error("error rendering template", "error", err)
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
return
}
category := r.URL.Query().Get("index")
if category == "" {
sendErrorResponse(w, "Unknown index", http.StatusBadRequest, nil)
return
}
// Check if a valid index is sent.
if ok := validIndex(category); !ok {
sendErrorResponse(w, "Unknown index", http.StatusBadRequest, nil)
return
}
// Fetch a list of stocks from DB.
stocks, err := app.getRandomStocks(STOCKS_COUNT, category)
if err != nil {
app.lo.Error("error generating stocks", "error", err)
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
// Fetch returns for various time periods.
for _, days := range returnPeriods {
returns, err := app.getPortfolioReturns(stocks, days)
if err != nil {
app.lo.Error("error fetching portfolio returns", "error", err)
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
portfolio[days] = returns
avgPortfolioReturns[days] = computeAvg(returns)
// Add individual stock returns.
for _, s := range returns {
if val, ok := avgStockReturns[s.Symbol]; ok {
val[days] = s.Percent
} else {
avgStockReturns[s.Symbol] = map[int]float64{days: s.Percent}
}
}
}
// Fetch index returns for various time periods.
for _, days := range returnPeriods {
returns, err := app.getIndexReturns([]string{category}, days)
if err != nil {
app.lo.Error("error fetching index returns", "error", err)
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
index[days] = returns
avgIndexReturns[days] = computeAvg(returns)
}
// Fetch the daily returns over 3 years.
dailyPortfolioReturns, err = app.getDailyValue(stocks, 1825)
if err != nil {
app.lo.Error("error fetching daily returns", "error", err)
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
dailyIndexReturns, err = app.getDailyValue([]string{category}, 1825)
if err != nil {
app.lo.Error("error fetching daily returns", "error", err)
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
if len(dailyIndexReturns) == 0 || len(dailyPortfolioReturns) == 0 {
app.lo.Error("error fetching daily returns", "error", err)
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
// Generate a unique UUID for the portfolio and save to `share` table.
data := portfolioTpl{
DailyPortfolioReturns: dailyPortfolioReturns,
DailyIndexReturns: dailyIndexReturns,
AvgStockReturns: avgStockReturns,
AvgIndexReturns: avgIndexReturns,
AvgPortfolioReturns: avgPortfolioReturns,
CurrentPortfolioAmount: int64(dailyPortfolioReturns[len(dailyPortfolioReturns)-1].CurrentInvested),
CurrentIndexAmount: int64(dailyIndexReturns[len(dailyIndexReturns)-1].CurrentInvested),
Category: category,
}
id, err := app.savePortfolio(data)
if err != nil {
app.lo.Error("error saving data", "error", err)
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
data.ShareID = id
if err := app.tpl.ExecuteTemplate(w, "portfolio", data); err != nil {
app.lo.Error("error rendering template", "error", err)
sendErrorResponse(w, "Internal Server Error.", http.StatusInternalServerError, nil)
return
}
}