123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- package websocket
- import (
- "bufio"
- "fmt"
- "io"
- "net/http"
- )
- func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request, config *Config, handshake func(*Config, *http.Request) error) (conn *Conn, err error) {
- var hs serverHandshaker = &hybiServerHandshaker{Config: config}
- code, err := hs.ReadHandshake(buf.Reader, req)
- if err == ErrBadWebSocketVersion {
- fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
- fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion)
- buf.WriteString("\r\n")
- buf.WriteString(err.Error())
- buf.Flush()
- return
- }
- if err != nil {
- fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
- buf.WriteString("\r\n")
- buf.WriteString(err.Error())
- buf.Flush()
- return
- }
- if handshake != nil {
- err = handshake(config, req)
- if err != nil {
- code = http.StatusForbidden
- fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
- buf.WriteString("\r\n")
- buf.Flush()
- return
- }
- }
- err = hs.AcceptHandshake(buf.Writer)
- if err != nil {
- code = http.StatusBadRequest
- fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
- buf.WriteString("\r\n")
- buf.Flush()
- return
- }
- conn = hs.NewServerConn(buf, rwc, req)
- return
- }
- type Server struct {
-
- Config
-
-
-
- Handshake func(*Config, *http.Request) error
-
- Handler
- }
- func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
- s.serveWebSocket(w, req)
- }
- func (s Server) serveWebSocket(w http.ResponseWriter, req *http.Request) {
- rwc, buf, err := w.(http.Hijacker).Hijack()
- if err != nil {
- panic("Hijack failed: " + err.Error())
- }
-
-
-
- defer rwc.Close()
- conn, err := newServerConn(rwc, buf, req, &s.Config, s.Handshake)
- if err != nil {
- return
- }
- if conn == nil {
- panic("unexpected nil conn")
- }
- s.Handler(conn)
- }
- type Handler func(*Conn)
- func checkOrigin(config *Config, req *http.Request) (err error) {
- config.Origin, err = Origin(config, req)
- if err == nil && config.Origin == nil {
- return fmt.Errorf("null origin")
- }
- return err
- }
- func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
- s := Server{Handler: h, Handshake: checkOrigin}
- s.serveWebSocket(w, req)
- }
|