http.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // An HTTP-based signaling channel for the WebRTC server. It imitates the
  2. // broker as seen by clients, but it doesn't connect them to an
  3. // intermediate WebRTC proxy, rather connects them directly to this WebRTC
  4. // server. This code should be deleted when we have proxies in place.
  5. package main
  6. import (
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "github.com/keroserene/go-webrtc"
  12. )
  13. type httpHandler struct {
  14. config *webrtc.Configuration
  15. }
  16. func (h *httpHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  17. switch req.Method {
  18. case "GET":
  19. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  20. w.WriteHeader(http.StatusOK)
  21. w.Write([]byte(`HTTP signaling channel
  22. Send a POST request containing an SDP offer. The response will
  23. contain an SDP answer.
  24. `))
  25. return
  26. case "POST":
  27. break
  28. default:
  29. http.Error(w, "Bad request.", http.StatusBadRequest)
  30. return
  31. }
  32. // POST handling begins here.
  33. body, err := ioutil.ReadAll(http.MaxBytesReader(w, req.Body, 100000))
  34. if err != nil {
  35. http.Error(w, "Bad request.", http.StatusBadRequest)
  36. return
  37. }
  38. offer := webrtc.DeserializeSessionDescription(string(body))
  39. if offer == nil {
  40. http.Error(w, "Bad request.", http.StatusBadRequest)
  41. return
  42. }
  43. pc, err := makePeerConnectionFromOffer(offer, h.config)
  44. if err != nil {
  45. http.Error(w, fmt.Sprintf("Cannot create offer: %s", err), http.StatusInternalServerError)
  46. return
  47. }
  48. log.Println("answering HTTP POST")
  49. w.WriteHeader(http.StatusOK)
  50. w.Write([]byte(pc.LocalDescription().Serialize()))
  51. }
  52. func receiveSignalsHTTP(addr string, config *webrtc.Configuration) error {
  53. http.Handle("/", &httpHandler{config})
  54. log.Printf("listening HTTP on %s", addr)
  55. return http.ListenAndServe(addr, nil)
  56. }