main.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. // Copyright 2013 The Gorilla WebSocket 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 main
  5. import (
  6. "flag"
  7. "html/template"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "os"
  12. "strconv"
  13. "time"
  14. "github.com/gorilla/websocket"
  15. )
  16. const (
  17. // Time allowed to write the file to the client.
  18. writeWait = 10 * time.Second
  19. // Time allowed to read the next pong message from the client.
  20. pongWait = 60 * time.Second
  21. // Send pings to client with this period. Must be less than pongWait.
  22. pingPeriod = (pongWait * 9) / 10
  23. // Poll file for changes with this period.
  24. filePeriod = 10 * time.Second
  25. )
  26. var (
  27. addr = flag.String("addr", ":8080", "http service address")
  28. homeTempl = template.Must(template.New("").Parse(homeHTML))
  29. filename string
  30. upgrader = websocket.Upgrader{
  31. ReadBufferSize: 1024,
  32. WriteBufferSize: 1024,
  33. }
  34. )
  35. func readFileIfModified(lastMod time.Time) ([]byte, time.Time, error) {
  36. fi, err := os.Stat(filename)
  37. if err != nil {
  38. return nil, lastMod, err
  39. }
  40. if !fi.ModTime().After(lastMod) {
  41. return nil, lastMod, nil
  42. }
  43. p, err := ioutil.ReadFile(filename)
  44. if err != nil {
  45. return nil, fi.ModTime(), err
  46. }
  47. return p, fi.ModTime(), nil
  48. }
  49. func reader(ws *websocket.Conn) {
  50. defer ws.Close()
  51. ws.SetReadLimit(512)
  52. ws.SetReadDeadline(time.Now().Add(pongWait))
  53. ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
  54. for {
  55. _, _, err := ws.ReadMessage()
  56. if err != nil {
  57. break
  58. }
  59. }
  60. }
  61. func writer(ws *websocket.Conn, lastMod time.Time) {
  62. lastError := ""
  63. pingTicker := time.NewTicker(pingPeriod)
  64. fileTicker := time.NewTicker(filePeriod)
  65. defer func() {
  66. pingTicker.Stop()
  67. fileTicker.Stop()
  68. ws.Close()
  69. }()
  70. for {
  71. select {
  72. case <-fileTicker.C:
  73. var p []byte
  74. var err error
  75. p, lastMod, err = readFileIfModified(lastMod)
  76. if err != nil {
  77. if s := err.Error(); s != lastError {
  78. lastError = s
  79. p = []byte(lastError)
  80. }
  81. } else {
  82. lastError = ""
  83. }
  84. if p != nil {
  85. ws.SetWriteDeadline(time.Now().Add(writeWait))
  86. if err := ws.WriteMessage(websocket.TextMessage, p); err != nil {
  87. return
  88. }
  89. }
  90. case <-pingTicker.C:
  91. ws.SetWriteDeadline(time.Now().Add(writeWait))
  92. if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  93. return
  94. }
  95. }
  96. }
  97. }
  98. func serveWs(w http.ResponseWriter, r *http.Request) {
  99. ws, err := upgrader.Upgrade(w, r, nil)
  100. if err != nil {
  101. if _, ok := err.(websocket.HandshakeError); !ok {
  102. log.Println(err)
  103. }
  104. return
  105. }
  106. var lastMod time.Time
  107. if n, err := strconv.ParseInt(r.FormValue("lastMod"), 16, 64); err == nil {
  108. lastMod = time.Unix(0, n)
  109. }
  110. go writer(ws, lastMod)
  111. reader(ws)
  112. }
  113. func serveHome(w http.ResponseWriter, r *http.Request) {
  114. if r.URL.Path != "/" {
  115. http.Error(w, "Not found", 404)
  116. return
  117. }
  118. if r.Method != "GET" {
  119. http.Error(w, "Method not allowed", 405)
  120. return
  121. }
  122. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  123. p, lastMod, err := readFileIfModified(time.Time{})
  124. if err != nil {
  125. p = []byte(err.Error())
  126. lastMod = time.Unix(0, 0)
  127. }
  128. var v = struct {
  129. Host string
  130. Data string
  131. LastMod string
  132. }{
  133. r.Host,
  134. string(p),
  135. strconv.FormatInt(lastMod.UnixNano(), 16),
  136. }
  137. homeTempl.Execute(w, &v)
  138. }
  139. func main() {
  140. flag.Parse()
  141. if flag.NArg() != 1 {
  142. log.Fatal("filename not specified")
  143. }
  144. filename = flag.Args()[0]
  145. http.HandleFunc("/", serveHome)
  146. http.HandleFunc("/ws", serveWs)
  147. if err := http.ListenAndServe(*addr, nil); err != nil {
  148. log.Fatal(err)
  149. }
  150. }
  151. const homeHTML = `<!DOCTYPE html>
  152. <html lang="en">
  153. <head>
  154. <title>WebSocket Example</title>
  155. </head>
  156. <body>
  157. <pre id="fileData">{{.Data}}</pre>
  158. <script type="text/javascript">
  159. (function() {
  160. var data = document.getElementById("fileData");
  161. var conn = new WebSocket("ws://{{.Host}}/ws?lastMod={{.LastMod}}");
  162. conn.onclose = function(evt) {
  163. data.textContent = 'Connection closed';
  164. }
  165. conn.onmessage = function(evt) {
  166. console.log('file updated');
  167. data.textContent = evt.data;
  168. }
  169. })();
  170. </script>
  171. </body>
  172. </html>
  173. `