From 2b876382ff8c4e63b77505a685b8b51a65188188 Mon Sep 17 00:00:00 2001 From: damir Date: Sat, 4 Apr 2026 14:52:04 +0000 Subject: [PATCH] Update main.go --- main.go | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 65 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index 593ba19..536b67a 100644 --- a/main.go +++ b/main.go @@ -1,20 +1,79 @@ package main import ( + "encoding/json" "fmt" "net/http" - "time" + "sync" + + "github.com/pion/webrtc/v3" ) func main() { + // Статический HTML фронтенд http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Hello from Dockerized Go App!") + http.ServeFile(w, r, "index.html") }) - http.HandleFunc("/time", func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Current time: %s", time.Now().Format(time.RFC1123)) - }) + // Сигналлинг: прием Offer и возврат Answer + http.HandleFunc("/sdp", handleSignaling) - fmt.Println("Server starting on :8080...") + fmt.Println("Server starting on :8080 at auth.shaiheprjct.ru") http.ListenAndServe(":8080", nil) +} + +func handleSignaling(w http.ResponseWriter, r *http.Request) { + var offer webrtc.SessionDescription + if err := json.NewDecoder(r.Body).Decode(&offer); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + config := webrtc.Configuration{ + ICEServers: []webrtc.ICEServer{ + {URLs: []string{"stun:stun.l.google.com:19302"}}, + }, + } + + peerConnection, err := webrtc.NewPeerConnection(config) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Обработка входящего DataChannel + peerConnection.OnDataChannel(func(d *webrtc.DataChannel) { + fmt.Printf("New DataChannel %s %d\n", d.Label(), d.ID()) + + d.OnOpen(func() { + fmt.Printf("Data channel '%s' open\n", d.Label()) + }) + + d.OnMessage(func(msg webrtc.DataChannelMessage) { + fmt.Printf("Message from DataChannel '%s': %s\n", d.Label(), string(msg.Data)) + // Эхо-ответ (имитация UDP ответа) + d.SendText("Echo: " + string(msg.Data)) + }) + }) + + // Установка удаленного описания (Offer) + err = peerConnection.SetRemoteDescription(offer) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Создание Answer + answer, err := peerConnection.CreateAnswer(nil) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Сбор ICE кандидатов (упрощенно: ждем завершения сбора перед отправкой Answer) + gatherComplete := webrtc.GatheringCompletePromise(peerConnection) + peerConnection.SetLocalDescription(answer) + <-gatherComplete + + json.NewEncoder(w).Encode(peerConnection.LocalDescription()) } \ No newline at end of file