properly handling serving websocket and frontend at the same time

This commit is contained in:
Chris kerr 2024-07-24 22:09:54 -04:00
parent 3015cf8c85
commit a61c539c54
4 changed files with 29 additions and 23 deletions

View File

@ -1,7 +1,5 @@
mongodb:
uri: "mongodb://localhost:27017/"
database: "grain"
relay:
server:
port: ":8080"
web:
port: ":8181"

38
main.go
View File

@ -27,23 +27,33 @@ func main() {
}
defer db.DisconnectDB()
// Run the WebSocket server in a goroutine
go func() {
fmt.Printf("WebSocket server is running on ws://localhost%s\n", config.Relay.Port)
err := http.ListenAndServe(config.Relay.Port, websocket.Handler(relay.Listener))
if err != nil {
fmt.Println("Error starting WebSocket server:", err)
}
}()
// Run the HTTP server for serving static files and home page
// Create a new ServeMux
mux := http.NewServeMux()
mux.HandleFunc("/", web.RootHandler)
// Handle the root path
mux.HandleFunc("/", ListenAndServe)
// Serve static files
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("web/static"))))
fmt.Printf("Http server is running on http://localhost%s\n", config.Web.Port)
err = http.ListenAndServe(config.Web.Port, mux)
// 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 web server:", err)
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" {
websocket.Handler(relay.WebSocketHandler).ServeHTTP(w, r)
} else {
web.RootHandler(w, r)
}
}

View File

@ -8,7 +8,8 @@ import (
"golang.org/x/net/websocket"
)
func Listener(ws *websocket.Conn) {
// WebSocketHandler handles incoming WebSocket connections
func WebSocketHandler(ws *websocket.Conn) {
defer ws.Close()
var msg string

View File

@ -11,12 +11,9 @@ type Config struct {
URI string `yaml:"uri"`
Database string `yaml:"database"`
} `yaml:"mongodb"`
Relay struct {
Server struct {
Port string `yaml:"port"`
} `yaml:"relay"`
Web struct {
Port string `yaml:"port"`
} `yaml:"web"`
} `yaml:"server"`
}
func LoadConfig(filename string) (*Config, error) {