package main import ( "log" "net/http" "os" "path/filepath" "strconv" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true // Note: In production, you'd want to check the origin. }, } // handleWebSocket handles WebSocket requests from the peer. func handleWebSocket(w http.ResponseWriter, r *http.Request) { log.Println("Websocket connection!", r.RemoteAddr) conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("Upgrade error:", err) return } defer conn.Close() for { mt, message, err := conn.ReadMessage() if err != nil { log.Println("Read error:", err) break } log.Printf("recv: %s", message) err = conn.WriteMessage(mt, message) if err != nil { log.Println("Write error:", err) break } } } // LoggingHandler logs requests and delegates them to the underlying handler. type LoggingHandler struct { handler http.Handler } func (lh *LoggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { log.Printf("Serving file: %s", r.URL.Path) lh.handler.ServeHTTP(w, r) } // noDirListing wraps an http.FileServer handler to prevent directory listings func noDirListing(h http.Handler, root string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Serve index.html when root is requested if r.URL.Path == "/" { http.ServeFile(w, r, filepath.Join(root, "index.html")) return } // Check if the path is a directory path := filepath.Join(root, r.URL.Path) if info, err := os.Stat(path); err == nil && info.IsDir() { http.NotFound(w, r) // Return 404 for directories other than root return } h.ServeHTTP(w, r) } } func main() { dir := "./" port := 6789 addr := ":" + strconv.Itoa(port) log.Printf("Starting server on %s", addr) // Set up file server and WebSocket endpoint fs := http.FileServer(http.Dir(dir)) // loggingHandler := &LoggingHandler{handler: fs} // http.Handle("/", loggingHandler) http.Handle("/", noDirListing(fs, dir)) http.HandleFunc("/ws", handleWebSocket) // Configure and start the HTTP server server := &http.Server{ Addr: addr, Handler: nil, // nil uses the default ServeMux, which we configured above } log.Printf("Server is configured and serving on port %d...", port) log.Fatal(server.ListenAndServe()) }