-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
165 lines (136 loc) · 5.83 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
package main
import (
"log"
"net/http"
"strings"
"time"
"tosdrgo/handlers"
"tosdrgo/handlers/auth"
"tosdrgo/handlers/metrics"
"tosdrgo/handlers/middleware"
"tosdrgo/internal/config"
db2 "tosdrgo/internal/db"
"tosdrgo/internal/email"
"tosdrgo/internal/logger"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var IsBeta = false
func init() {
if err := config.LoadConfig(); err != nil {
log.Fatalf("Failed to load configuration: %v", err)
}
auth.Init(
config.AppConfig.Login.Domain,
config.AppConfig.Login.ClientID,
config.AppConfig.Login.ClientSecret,
config.AppConfig.Login.RedirectURI,
config.AppConfig.Login.SessionKey,
config.AppConfig.Login.LogoutReturn,
)
if err := email.Init(); err != nil {
log.Fatalf("Failed to initialize email client: %v", err)
}
}
func setCSSContentType(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, ".css") {
w.Header().Set("Content-Type", "text/css")
}
next.ServeHTTP(w, r)
})
}
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
logger.LogRequest(r, time.Since(start))
})
}
// Add basic auth middleware for metrics
func basicAuthMiddleware(username, password string) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if !ok || user != username || pass != password {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}
func main() {
if err := db2.InitDB(); err != nil {
log.Fatalf("Failed to initialize database: %v", err)
}
defer db2.CloseDB()
// Initial indexing
db2.IndexSearch()
// Start background indexing
go func() {
ticker := time.NewTicker(12 * time.Hour)
defer ticker.Stop()
for range ticker.C {
logger.LogDebug("Running scheduled search index update")
db2.IndexSearch()
}
}()
r := mux.NewRouter()
// Add metrics middleware to all routes
r.Use(metrics.MetricsMiddleware)
r.Use(loggingMiddleware)
// Create a subrouter for metrics with authentication
metricsRouter := r.PathPrefix("/metrics").Subrouter()
metricsRouter.Use(basicAuthMiddleware(
config.AppConfig.MetricsUsername,
config.AppConfig.MetricsPassword,
))
metricsRouter.Handle("", promhttp.Handler())
r.HandleFunc("/v1/health", handlers.HealthCheckHandler).Methods("GET").Name("health")
// Serve static files with content type middleware and minification for CSS
r.PathPrefix("/static/css/").Handler(handlers.MinifyMiddlewareHandler(
setCSSContentType(http.StripPrefix("/static/css/", http.FileServer(http.Dir("static/css"))))))
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
// Shield endpoints (without language prefix)
r.HandleFunc("/{lang:[a-z]{2}}/shield/{serviceID}", handlers.ShieldHandler).Methods("GET")
r.HandleFunc("/legacyshield/{lang:[a-z]{2}}_{serviceID}.svg", handlers.ShieldHandler).Methods("GET")
// Add redirects for non-language-prefixed routes
r.HandleFunc("/service/{serviceID}", handlers.DetectLanguageAndRedirectWithPath).Methods("GET")
r.HandleFunc("/about", handlers.DetectLanguageAndRedirectWithPath).Methods("GET")
r.HandleFunc("/thanks", handlers.DetectLanguageAndRedirectWithPath).Methods("GET")
r.HandleFunc("/sites/{sitename}", handlers.DetectLanguageAndRedirectWithPath).Methods("GET")
// Root redirect to browser language
r.HandleFunc("/", handlers.DetectLanguageAndRedirect)
// Language-prefixed routes
r.HandleFunc("/{lang:[a-z]{2}}", handlers.MinifyMiddleware(handlers.HomeHandler)).Name("home")
r.HandleFunc("/{lang:[a-z]{2}}/", handlers.MinifyMiddleware(handlers.HomeHandler))
r.HandleFunc("/{lang:[a-z]{2}}/about", handlers.MinifyMiddleware(handlers.AboutHandler)).Name("about")
r.HandleFunc("/{lang:[a-z]{2}}/thanks", handlers.MinifyMiddleware(handlers.ThanksHandler)).Name("thanks")
r.HandleFunc("/{lang:[a-z]{2}}/service/{serviceID}", handlers.MinifyMiddleware(handlers.ServiceHandler)).Name("service")
r.HandleFunc("/{lang:[a-z]{2}}/sites/{sitename}", handlers.MinifyMiddleware(handlers.SiteHandler))
r.HandleFunc("/{lang:[a-z]{2}}/new_service", handlers.MinifyMiddleware(handlers.NewServiceHandler)).Methods("GET", "POST").Name("new_service")
r.HandleFunc("/{lang:[a-z]{2}}/services/{grade}", handlers.MinifyMiddleware(handlers.GradedServicesHandler))
searchRouter := r.PathPrefix("/{lang:[a-z]{2}}/search").Subrouter()
searchRouter.Use(middleware.RateLimitMiddleware)
searchRouter.HandleFunc("/{term}", handlers.MinifyMiddleware(handlers.SearchHandler))
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Track 404 paths
metrics.NotFoundPaths.WithLabelValues(r.URL.Path, r.Method).Inc()
handlers.RenderErrorPage(w, "en", http.StatusNotFound, "The requested page was not found", nil)
})
//goland:noinspection GoBoolExpressions
handlers.SetIsBeta(IsBeta)
// Auth routes
r.HandleFunc("/login", handlers.LoginHandler).Methods("GET").Name("login")
r.HandleFunc("/logout", handlers.LogoutHandler).Methods("GET").Name("logout")
r.HandleFunc("/auth/callback", handlers.CallbackHandler).Methods("GET").Name("auth_callback")
r.HandleFunc("/{lang:[a-z]{2}}/profile", handlers.ProfileHandler).Methods("GET").Name("profile")
// Dashboard route
r.HandleFunc("/{lang:[a-z]{2}}/dashboard", handlers.DashboardHandler).Methods("GET").Name("dashboard")
r.HandleFunc("/api/submissions/{id}/{action}", handlers.HandleSubmissionAction).Methods("POST").Name("submission_action")
// Start the server
log.Printf("Server starting on 0.0.0.0:80")
log.Fatal(http.ListenAndServe("0.0.0.0:80", r))
}