generated from damir/go_app_template
Update main.go
This commit is contained in:
71
main.go
71
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())
|
||||
}
|
||||
Reference in New Issue
Block a user