You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

websocket.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright (c) 2015 Niels Freier
  2. // Copyright (c) 2015 Edmund Huber
  3. // released under the MIT license
  4. package irc
  5. import (
  6. "net/http"
  7. "time"
  8. "github.com/gorilla/websocket"
  9. )
  10. var upgrader = websocket.Upgrader{
  11. ReadBufferSize: 2048,
  12. WriteBufferSize: 2048,
  13. // If a WS session contains sensitive information, and you choose to use
  14. // cookies for authentication (during the HTTP(S) upgrade request), then
  15. // you should check that Origin is a domain under your control. If it
  16. // isn't, then it is possible for users of your site, visiting a naughty
  17. // Origin, to have a WS opened using their credentials. See
  18. // http://www.christian-schneider.net/CrossSiteWebSocketHijacking.html#main.
  19. // We don't care about Origin because the (IRC) authentication is contained
  20. // in the WS stream -- the WS session is not privileged when it is opened.
  21. CheckOrigin: func(r *http.Request) bool { return true },
  22. }
  23. // WSContainer holds the websocket.
  24. type WSContainer struct {
  25. *websocket.Conn
  26. }
  27. // Read reads new incoming messages.
  28. func (ws WSContainer) Read(msg []byte) (int, error) {
  29. ty, bytes, err := ws.ReadMessage()
  30. if ty == websocket.TextMessage {
  31. n := copy(msg, []byte(string(bytes)+"\r\n\r\n"))
  32. return n, err
  33. }
  34. // Binary, and other kinds of messages, are thrown away.
  35. return 0, nil
  36. }
  37. // Write writes lines out to the websocket.
  38. func (ws WSContainer) Write(msg []byte) (int, error) {
  39. err := ws.WriteMessage(websocket.TextMessage, msg)
  40. return len(msg), err
  41. }
  42. // SetDeadline sets the read and write deadline on this websocket.
  43. func (ws WSContainer) SetDeadline(t time.Time) error {
  44. if err := ws.SetWriteDeadline(t); err != nil {
  45. return err
  46. }
  47. return ws.SetReadDeadline(t)
  48. }