package main import ( "encoding/json" "fmt" "io" "log" "net/http" "time" ) var server = New(10 * time.Second) func wsHandler(responseWriter http.ResponseWriter, request *http.Request) { conn, err := server.Upgrader.Upgrade(responseWriter, request, nil) if err != nil { fmt.Println("Error during connection upgrade:", err) return } server.HandleNew(conn) } type DownloadReq struct { Link string `json:"link"` } func handleDownload(responseWriter http.ResponseWriter, request *http.Request) { body, err := io.ReadAll(request.Body) if err != nil { log.Printf("Error reading request body: %v", err) http.Error(responseWriter, "Error reading request body", http.StatusBadRequest) return } defer request.Body.Close() req := DownloadReq{} err = json.Unmarshal(body, &req) if err != nil { log.Printf("Error parsing JSON: %v", err) http.Error(responseWriter, "Error parsing JSON", http.StatusBadRequest) return } server.Broadcast <- req.Link } func init() { // log.SetFlags(log.Lmicroseconds | log.Lshortfile) log.SetFlags(log.Lmicroseconds) } // Mainly used to detect memory leaks // func instrument() { // numGoroutines := runtime.NumGoroutine() // var m runtime.MemStats // runtime.ReadMemStats(&m) // malloc := float64(m.Alloc) // ramUsedMB := malloc / 1024 / 1024 // kbPerGoroutine := malloc / 1024 / float64(numGoroutines) // log.Printf("Number of active goroutines: %d; RAM used: %.2f MB; KB per goroutine: %.2f", numGoroutines, ramUsedMB, kbPerGoroutine) // } func main() { // go func() { // for { // time.Sleep(1 * time.Second) // instrument() // } // }() http.HandleFunc("/ws", wsHandler) http.HandleFunc("/download", handleDownload) log.Println("Server starting on :8080") err := http.ListenAndServe(":8080", nil) if err != nil { log.Println("Error starting server:", err) } }