server.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package websocket
  5. import (
  6. "bufio"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. )
  11. func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request) (conn *Conn, err error) {
  12. config := new(Config)
  13. var hs serverHandshaker = &hybiServerHandshaker{Config: config}
  14. code, err := hs.ReadHandshake(buf.Reader, req)
  15. if err == ErrBadWebSocketVersion {
  16. fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
  17. fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion)
  18. buf.WriteString("\r\n")
  19. buf.WriteString(err.Error())
  20. buf.Flush()
  21. return
  22. }
  23. if err != nil {
  24. hs = &hixie76ServerHandshaker{Config: config}
  25. code, err = hs.ReadHandshake(buf.Reader, req)
  26. }
  27. if err != nil {
  28. hs = &hixie75ServerHandshaker{Config: config}
  29. code, err = hs.ReadHandshake(buf.Reader, req)
  30. }
  31. if err != nil {
  32. fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
  33. buf.WriteString("\r\n")
  34. buf.WriteString(err.Error())
  35. buf.Flush()
  36. return
  37. }
  38. config.Protocol = nil
  39. err = hs.AcceptHandshake(buf.Writer)
  40. if err != nil {
  41. code = http.StatusBadRequest
  42. fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
  43. buf.WriteString("\r\n")
  44. buf.Flush()
  45. return
  46. }
  47. conn = hs.NewServerConn(buf, rwc, req)
  48. return
  49. }
  50. // Handler is an interface to a WebSocket.
  51. type Handler func(*Conn)
  52. // ServeHTTP implements the http.Handler interface for a Web Socket
  53. func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  54. rwc, buf, err := w.(http.Hijacker).Hijack()
  55. if err != nil {
  56. panic("Hijack failed: " + err.Error())
  57. return
  58. }
  59. // The server should abort the WebSocket connection if it finds
  60. // the client did not send a handshake that matches with protocol
  61. // specification.
  62. defer rwc.Close()
  63. conn, err := newServerConn(rwc, buf, req)
  64. if err != nil {
  65. return
  66. }
  67. if conn == nil {
  68. panic("unexpected nil conn")
  69. }
  70. h(conn)
  71. }