grain/main.go

78 lines
1.8 KiB
Go
Raw Normal View History

2024-07-19 22:07:04 +00:00
package main
import (
"fmt"
"log"
"net/http"
2024-07-23 17:30:29 +00:00
"grain/relay"
"grain/relay/db"
2024-07-25 03:04:26 +00:00
"grain/relay/handlers"
2024-07-23 17:30:29 +00:00
"grain/relay/utils"
2024-07-23 20:40:39 +00:00
"grain/web"
2024-07-19 22:07:04 +00:00
"golang.org/x/net/websocket"
2024-07-25 03:04:26 +00:00
"golang.org/x/time/rate"
2024-07-19 22:07:04 +00:00
)
2024-07-25 03:04:26 +00:00
var rl *utils.RateLimiter
2024-07-19 22:07:04 +00:00
func main() {
// Load configuration
config, err := utils.LoadConfig("config.yml")
if err != nil {
log.Fatal("Error loading config: ", err)
}
// Initialize MongoDB client
_, err = db.InitDB(config.MongoDB.URI, config.MongoDB.Database)
if err != nil {
log.Fatal("Error initializing database: ", err)
}
defer db.DisconnectDB()
2024-07-20 12:41:47 +00:00
2024-07-25 03:04:26 +00:00
// Initialize rate limiter
rl = utils.NewRateLimiter(rate.Limit(config.RateLimit.EventLimit), config.RateLimit.EventBurst, rate.Limit(config.RateLimit.WsLimit), config.RateLimit.WsBurst)
for _, kindLimit := range config.RateLimit.KindLimits {
rl.AddKindLimit(kindLimit.Kind, rate.Limit(kindLimit.Limit), kindLimit.Burst)
}
handlers.SetRateLimiter(rl)
// Create a new ServeMux
2024-07-23 20:40:39 +00:00
mux := http.NewServeMux()
// Handle the root path
mux.HandleFunc("/", ListenAndServe)
// Serve static files
2024-07-23 20:40:39 +00:00
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("web/static"))))
// Serve the favicon
mux.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/static/img/favicon.ico")
})
// Start the Relay
fmt.Printf("Server is running on http://localhost%s\n", config.Server.Port)
err = http.ListenAndServe(config.Server.Port, mux)
if err != nil {
fmt.Println("Error starting server:", err)
}
}
// Listener serves both WebSocket and HTML
func ListenAndServe(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Upgrade") == "websocket" {
2024-07-25 03:04:26 +00:00
websocket.Handler(func(ws *websocket.Conn) {
if !rl.AllowWs() {
ws.Close()
return
}
relay.WebSocketHandler(ws)
}).ServeHTTP(w, r)
} else {
web.RootHandler(w, r)
}
2024-07-19 22:07:04 +00:00
}