http.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. _, err := 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. if err != nil {
  26. log.Printf("GET request write failed with error: %v", err)
  27. }
  28. return
  29. case "POST":
  30. break
  31. default:
  32. http.Error(w, "Bad request.", http.StatusBadRequest)
  33. return
  34. }
  35. // POST handling begins here.
  36. body, err := ioutil.ReadAll(http.MaxBytesReader(w, req.Body, 100000))
  37. if err != nil {
  38. http.Error(w, "Bad request.", http.StatusBadRequest)
  39. return
  40. }
  41. offer := webrtc.DeserializeSessionDescription(string(body))
  42. if offer == nil {
  43. http.Error(w, "Bad request.", http.StatusBadRequest)
  44. return
  45. }
  46. pc, err := makePeerConnectionFromOffer(offer, h.config)
  47. if err != nil {
  48. http.Error(w, fmt.Sprintf("Cannot create offer: %s", err), http.StatusInternalServerError)
  49. return
  50. }
  51. log.Println("answering HTTP POST")
  52. w.WriteHeader(http.StatusOK)
  53. _, err = w.Write([]byte(pc.LocalDescription().Serialize()))
  54. if err != nil {
  55. log.Printf("answering HTTP POST write failed with error %v", err)
  56. }
  57. }
  58. func receiveSignalsHTTP(addr string, config *webrtc.Configuration) error {
  59. http.Handle("/", &httpHandler{config})
  60. log.Printf("listening HTTP on %s", addr)
  61. return http.ListenAndServe(addr, nil)
  62. }