diff --git a/internal/api/ws/ws.go b/internal/api/ws/ws.go index 0eb45aa7..1d945bfe 100644 --- a/internal/api/ws/ws.go +++ b/internal/api/ws/ws.go @@ -37,16 +37,21 @@ var log zerolog.Logger type Message struct { Type string `json:"type"` Value any `json:"value,omitempty"` - Raw []byte `json:"-"` } func (m *Message) String() (value string) { - _ = json.Unmarshal(m.Raw, &value) + if s, ok := m.Value.(string); ok { + return s + } return } func (m *Message) Unmarshal(v any) error { - return json.Unmarshal(m.Raw, v) + b, err := json.Marshal(m.Value) + if err != nil { + return err + } + return json.Unmarshal(b, v) } type WSHandler func(tr *Transport, msg *Message) error @@ -113,11 +118,8 @@ func apiWS(w http.ResponseWriter, r *http.Request) { }) for { - var raw struct { - Type string `json:"type"` - Value json.RawMessage `json:"value"` - } - if err = ws.ReadJSON(&raw); err != nil { + msg := new(Message) + if err = ws.ReadJSON(msg); err != nil { if !websocket.IsCloseError(err, websocket.CloseNoStatusReceived) { log.Trace().Err(err).Caller().Send() } @@ -125,8 +127,6 @@ func apiWS(w http.ResponseWriter, r *http.Request) { break } - msg := &Message{Type: raw.Type, Raw: raw.Value} - log.Trace().Str("type", msg.Type).Msg("[api] ws msg") if handler := wsHandlers[msg.Type]; handler != nil { diff --git a/internal/webrtc/webrtc_test.go b/internal/webrtc/webrtc_test.go new file mode 100644 index 00000000..e014c31c --- /dev/null +++ b/internal/webrtc/webrtc_test.go @@ -0,0 +1,38 @@ +package webrtc + +import ( + "encoding/json" + "testing" + + "github.com/AlexxIT/go2rtc/internal/api/ws" + pion "github.com/pion/webrtc/v3" + "github.com/stretchr/testify/require" +) + +func TestWebRTCAPIv1(t *testing.T) { + raw := `{"type":"webrtc/offer","value":"v=0\n..."}` + msg := new(ws.Message) + err := json.Unmarshal([]byte(raw), msg) + require.Nil(t, err) + + require.Equal(t, "v=0\n...", msg.String()) +} + +func TestWebRTCAPIv2(t *testing.T) { + raw := `{"type":"webrtc","value":{"type":"offer","sdp":"v=0\n...","ice_servers":[{"urls":["stun:stun.l.google.com:19302"]}]}}` + msg := new(ws.Message) + err := json.Unmarshal([]byte(raw), msg) + require.Nil(t, err) + + var offer struct { + Type string `json:"type"` + SDP string `json:"sdp"` + ICEServers []pion.ICEServer `json:"ice_servers"` + } + err = msg.Unmarshal(&offer) + require.Nil(t, err) + + require.Equal(t, "offer", offer.Type) + require.Equal(t, "v=0\n...", offer.SDP) + require.Equal(t, "stun:stun.l.google.com:19302", offer.ICEServers[0].URLs[0]) +}