您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package livereload
  2. import (
  3. "encoding/json"
  4. "regexp"
  5. "github.com/gorilla/websocket"
  6. )
  7. var regexHandshake = regexp.MustCompile(`"command"\s*:\s*"hello"`)
  8. /* ----------------------------------------------------------------------
  9. * WebSocket Server Tunnel
  10. * ----------------------------------------------------------------------*/
  11. type tunnel struct {
  12. socket *websocket.Conn
  13. message chan []byte
  14. }
  15. // connect reads/writes message for livereload.js.
  16. func (self *tunnel) connect() {
  17. // ***********************
  18. // WebSocket Tunnel#Write
  19. // ***********************
  20. go func() {
  21. for message := range self.message {
  22. if err := self.socket.WriteMessage(websocket.TextMessage, message); err != nil {
  23. break
  24. } else {
  25. if regexHandshake.Find(message) != nil {
  26. // Keep the tunnel opened after handshake(hello command).
  27. Reload()
  28. }
  29. }
  30. }
  31. self.socket.Close()
  32. }()
  33. // ***********************
  34. // WebSocket Tunnel#Read
  35. // ***********************
  36. for {
  37. _, message, err := self.socket.ReadMessage()
  38. if err != nil {
  39. break
  40. }
  41. switch true {
  42. case regexHandshake.Find(message) != nil:
  43. var bytes, _ = json.Marshal(&hello{
  44. Command: "hello",
  45. Protocols: []string{"http://livereload.com/protocols/official-7"},
  46. ServerName: "Rex#Livereload",
  47. })
  48. self.message <- bytes
  49. }
  50. }
  51. self.socket.Close()
  52. }