Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

80 lines
2.5KB

  1. /* ----------------------------------------------------------------------
  2. * ______ ___ __
  3. * / ____/___ / | ____ __ ___ __/ /_ ___ ________
  4. * / / __/ __ \/ /| | / __ \/ / / / | /| / / __ \/ _ \/ ___/ _ \
  5. * / /_/ / /_/ / ___ |/ / / / /_/ /| |/ |/ / / / / __/ / / __/
  6. * \____/\____/_/ |_/_/ /_/\__. / |__/|__/_/ /_/\___/_/ \___/
  7. * /____/
  8. *
  9. * (C) Copyright 2015 GoAnywhere (http://goanywhere.io).
  10. * ----------------------------------------------------------------------
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. * ----------------------------------------------------------------------*/
  23. package livereload
  24. import (
  25. "encoding/json"
  26. "regexp"
  27. "github.com/gorilla/websocket"
  28. )
  29. var regexHandshake = regexp.MustCompile(`"command"\s*:\s*"hello"`)
  30. /* ----------------------------------------------------------------------
  31. * WebSocket Server Tunnel
  32. * ----------------------------------------------------------------------*/
  33. type tunnel struct {
  34. socket *websocket.Conn
  35. message chan []byte
  36. }
  37. // connect reads/writes message for livereload.js.
  38. func (self *tunnel) connect() {
  39. // ***********************
  40. // WebSocket Tunnel#Write
  41. // ***********************
  42. go func() {
  43. for message := range self.message {
  44. if err := self.socket.WriteMessage(websocket.TextMessage, message); err != nil {
  45. break
  46. } else {
  47. if regexHandshake.Find(message) != nil {
  48. // Keep the tunnel opened after handshake(hello command).
  49. Reload()
  50. }
  51. }
  52. }
  53. self.socket.Close()
  54. }()
  55. // ***********************
  56. // WebSocket Tunnel#Read
  57. // ***********************
  58. for {
  59. _, message, err := self.socket.ReadMessage()
  60. if err != nil {
  61. break
  62. }
  63. switch true {
  64. case regexHandshake.Find(message) != nil:
  65. var bytes, _ = json.Marshal(&hello{
  66. Command: "hello",
  67. Protocols: []string{"http://livereload.com/protocols/official-7"},
  68. ServerName: "Rex#Livereload",
  69. })
  70. self.message <- bytes
  71. }
  72. }
  73. self.socket.Close()
  74. }