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: mongodb:
uri: "mongodb://localhost:27017/" uri: "mongodb://localhost:27017/"
database: "grain" database: "grain"
relay: server:
port: ":8080" port: ":8080"
web:
port: ":8181"

38
main.go
View File

@ -27,23 +27,33 @@ func main() {
} }
defer db.DisconnectDB() defer db.DisconnectDB()
// Run the WebSocket server in a goroutine // Create a new ServeMux
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
mux := http.NewServeMux() 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")))) 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) // Serve the favicon
err = http.ListenAndServe(config.Web.Port, mux) 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 { 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" "golang.org/x/net/websocket"
) )
func Listener(ws *websocket.Conn) { // WebSocketHandler handles incoming WebSocket connections
func WebSocketHandler(ws *websocket.Conn) {
defer ws.Close() defer ws.Close()
var msg string var msg string

View File

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