-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
321 lines (287 loc) · 9.52 KB
/
main.go
File metadata and controls
321 lines (287 loc) · 9.52 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
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
package main
import (
"compress/gzip"
"context"
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"sleeperpy/goapp/cli"
"sleeperpy/goapp/otel"
)
var logLevel string
var testMode bool
// HTTP client with connection pooling
var httpClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 20,
IdleConnTimeout: 90 * time.Second,
},
}
// Cache instances (types defined in types.go)
var borisTiersCache = &tiersCache{
data: make(map[string]map[string][][]string),
timestamp: make(map[string]time.Time),
ttl: 15 * time.Minute, // Cache tiers for 15 minutes
}
var dynastyValuesCache = &dynastyCache{
data: make(map[string]DynastyValue),
ttl: 24 * time.Hour, // Cache for 24 hours (values don't change frequently)
}
var sleeperPlayersCache = &playersCache{
ttl: 1 * time.Hour, // Cache players data for 1 hour
}
var rosterValueTrendCache = &valueTrendCache{
data: make(map[string]CachedRosterValue),
ttl: 24 * time.Hour, // Compare values over 24 hours
}
// gzipResponseWriter wraps http.ResponseWriter to support gzip compression
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func debugLog(format string, v ...interface{}) {
if logLevel == "debug" {
log.Printf(format, v...)
}
}
// --- Prometheus metrics ---
var (
totalVisitors = prometheus.NewCounter(prometheus.CounterOpts{
Name: "sleeperpy_total_visitors",
Help: "Total number of unique visitors to the site.",
})
totalLookups = prometheus.NewCounter(prometheus.CounterOpts{
Name: "sleeperpy_total_lookups",
Help: "Total number of /lookup requests.",
})
totalLeagues = prometheus.NewCounter(prometheus.CounterOpts{
Name: "sleeperpy_total_leagues",
Help: "Total number of leagues processed.",
})
totalTeams = prometheus.NewCounter(prometheus.CounterOpts{
Name: "sleeperpy_total_teams",
Help: "Total number of teams processed.",
})
totalErrors = prometheus.NewCounter(prometheus.CounterOpts{
Name: "sleeperpy_total_errors",
Help: "Total number of errors encountered.",
})
)
func init() {
prometheus.MustRegister(totalVisitors)
prometheus.MustRegister(totalLookups)
prometheus.MustRegister(totalLeagues)
prometheus.MustRegister(totalTeams)
prometheus.MustRegister(totalErrors)
}
var funcMap = template.FuncMap{
"safe": func(s string) template.HTML { return template.HTML(s) },
"float64": func(i int) float64 { return float64(i) },
"mul": func(a, b float64) float64 { return a * b },
"div": func(a, b float64) float64 {
if b == 0 {
return 0
}
return a / b
},
"parseWinProb": func(s string) int {
// s is like "62% You 🏆" or "38% Opponent 💀"
parts := strings.Fields(s)
if len(parts) > 0 && strings.HasSuffix(parts[0], "%") {
n, err := strconv.Atoi(strings.TrimSuffix(parts[0], "%"))
if err == nil {
return n
}
}
return 50
},
"winProbColor": func(s string) string {
// Green for >60, yellow for 40-60, red for <40
p := 50
parts := strings.Fields(s)
if len(parts) > 0 && strings.HasSuffix(parts[0], "%") {
n, err := strconv.Atoi(strings.TrimSuffix(parts[0], "%"))
if err == nil {
p = n
}
}
if p > 60 {
return "#3ae87a" // green
} else if p < 40 {
return "#e83a3a" // red
}
return "#e8c63a" // yellow
},
"parseWinEmoji": func(s string) string {
// s is like "62% You 🏆" or "38% Opponent 💀"
parts := strings.Fields(s)
if len(parts) > 2 {
return parts[2]
}
return "🤝"
},
"absInt": func(n int) int {
if n < 0 {
return -n
}
return n
},
"contains": func(s, substr string) bool {
return strings.Contains(s, substr)
},
"formatTime": func(t time.Time) string {
if t.IsZero() {
return "Unknown"
}
// Format as relative time
now := time.Now()
diff := now.Sub(t)
if diff < time.Minute {
return "just now"
} else if diff < time.Hour {
mins := int(diff.Minutes())
if mins == 1 {
return "1 min ago"
}
return fmt.Sprintf("%d mins ago", mins)
} else if diff < 24*time.Hour {
hours := int(diff.Hours())
if hours == 1 {
return "1 hour ago"
}
return fmt.Sprintf("%d hours ago", hours)
} else if diff < 7*24*time.Hour {
days := int(diff.Hours() / 24)
if days == 1 {
return "1 day ago"
}
return fmt.Sprintf("%d days ago", days)
}
return t.Format("Jan 2, 2006")
},
"add": func(a, b int) int { return a + b },
}
var templates = template.Must(template.New("").Funcs(funcMap).ParseGlob("templates/*.html"))
func main() {
flag.StringVar(&logLevel, "log", "info", "Log level: info or debug")
flag.BoolVar(&testMode, "test", false, "Run in test mode with mock data")
flag.Parse()
// Check if CLI mode
args := flag.Args()
if len(args) > 0 && args[0] == "cli" {
// Initialize API client for CLI
cli.API = NewAPIClient()
// Run CLI mode
os.Exit(cli.Run(args[1:]))
}
// Initialize OpenTelemetry (only if OTEL_EXPORTER_OTLP_ENDPOINT is set)
ctx := context.Background()
if os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") != "" {
cleanup := otel.Init(ctx)
defer cleanup()
otel.InitMetrics()
log.Println("[OTEL] OpenTelemetry initialized")
}
// Otherwise run web server
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
// Initialize test mode if enabled
if testMode {
initTestMode()
log.Printf("[TEST MODE] Mock API endpoints registered")
http.HandleFunc("/api/mock/", mockAPIHandler)
http.HandleFunc("/boris/mock/", mockBorisTiersHandler)
}
// Static file server with cache headers
fs := http.FileServer(http.Dir("static"))
staticHandler := http.StripPrefix("/static/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set cache headers for static assets (1 year for immutable assets)
w.Header().Set("Cache-Control", "public, max-age=31536000")
fs.ServeHTTP(w, r)
}))
http.Handle("/static/", staticHandler)
// Gzip middleware
gzipMiddleware := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if client accepts gzip
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
}
// Create gzip writer
gz := gzip.NewWriter(w)
defer gz.Close()
// Wrap response writer
gzw := &gzipResponseWriter{Writer: gz, ResponseWriter: w}
w.Header().Set("Content-Encoding", "gzip")
w.Header().Del("Content-Length") // Let gzip set the length
next.ServeHTTP(gzw, r)
})
}
// Wrap handlers with gzip + OTEL instrumentation if enabled
wrapHandler := func(name string, handler http.HandlerFunc) http.Handler {
h := http.Handler(http.HandlerFunc(handler))
// Add gzip compression
h = gzipMiddleware(h)
// Add OTEL if configured
if os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") != "" {
h = otelhttp.NewHandler(h, name)
}
return h
}
http.Handle("/", wrapHandler("index", visitorLogging(indexHandler)))
http.Handle("/lookup", wrapHandler("lookup", lookupHandler))
http.Handle("/dashboard", wrapHandler("dashboard", dashboardHandler))
http.Handle("/signout", wrapHandler("signout", signoutHandler))
http.Handle("/privacy", wrapHandler("privacy", privacyHandler))
http.Handle("/terms", wrapHandler("terms", termsHandler))
http.Handle("/import", wrapHandler("import", importHandler))
http.Handle("/weekly-email", wrapHandler("weekly_email", weeklyEmailHandler))
http.Handle("/pricing", wrapHandler("pricing_redirect", pricingRedirectHandler))
http.Handle("/roadmap", wrapHandler("roadmap", roadmapHandler))
http.Handle("/about", wrapHandler("about", aboutHandler))
http.Handle("/faq", wrapHandler("faq", faqHandler))
http.Handle("/demo", wrapHandler("demo", demoHandler))
http.Handle("/status", wrapHandler("status", publicStatusHandler))
http.Handle("/robots.txt", wrapHandler("robots", robotsHandler))
http.Handle("/sitemap.xml", wrapHandler("sitemap", sitemapHandler))
http.Handle("/metrics", promhttp.Handler())
http.Handle("/admin", wrapHandler("admin", adminHandler))
http.Handle("/admin/api", wrapHandler("admin_api", adminAPIHandler))
if testMode {
log.Printf("Server running on 0.0.0.0:%s (log level: %s, TEST MODE ENABLED)", port, logLevel)
log.Printf(" → Use username 'testuser' to see mock data")
log.Printf(" → 3 test leagues will be loaded with mock tiers")
} else {
log.Printf("Server running on 0.0.0.0:%s (listening on all interfaces, log level: %s)", port, logLevel)
}
log.Fatal(http.ListenAndServe(":"+port, nil))
}
// Team mapping for DST/DEF
var TEAM_MAP = map[string]string{
"ARI": "Arizona Cardinals", "ATL": "Atlanta Falcons", "BAL": "Baltimore Ravens", "BUF": "Buffalo Bills",
"CAR": "Carolina Panthers", "CHI": "Chicago Bears", "CIN": "Cincinnati Bengals", "CLE": "Cleveland Browns",
"DAL": "Dallas Cowboys", "DEN": "Denver Broncos", "DET": "Detroit Lions", "GB": "Green Bay Packers",
"HOU": "Houston Texans", "IND": "Indianapolis Colts", "JAX": "Jacksonville Jaguars", "KC": "Kansas City Chiefs",
"LV": "Las Vegas Raiders", "LAC": "Los Angeles Chargers", "LAR": "Los Angeles Rams", "MIA": "Miami Dolphins",
"MIN": "Minnesota Vikings", "NE": "New England Patriots", "NO": "New Orleans Saints", "NYG": "New York Giants",
"NYJ": "New York Jets", "PHI": "Philadelphia Eagles", "PIT": "Pittsburgh Steelers", "SEA": "Seattle Seahawks",
"SF": "San Francisco 49ers", "TB": "Tampa Bay Buccaneers", "TEN": "Tennessee Titans", "WAS": "Washington Commanders",
}