Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

9 лет назад
9 лет назад
9 лет назад
9 лет назад
9 лет назад
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package livereload
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "compress/zlib"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "regexp"
  10. "strings"
  11. "github.com/Sirupsen/logrus"
  12. "github.com/goanywhere/env"
  13. )
  14. type writer struct {
  15. http.ResponseWriter
  16. host string
  17. }
  18. func (self *writer) addJavaScript(data []byte) []byte {
  19. javascript := fmt.Sprintf(`<script src="//%s%s"></script>
  20. </head>`, self.host, URL.JavaScript)
  21. logrus.Infof("JS: %s", javascript)
  22. return regexp.MustCompile(`</head>`).ReplaceAll(data, []byte(javascript))
  23. }
  24. func (self *writer) Write(data []byte) (size int, e error) {
  25. if strings.Contains(self.Header().Get("Content-Type"), "html") {
  26. var encoding = self.Header().Get("Content-Encoding")
  27. if encoding == "" {
  28. data = self.addJavaScript(data)
  29. } else {
  30. var reader io.ReadCloser
  31. var buffer *bytes.Buffer = new(bytes.Buffer)
  32. if encoding == "gzip" {
  33. // decode to add javascript reference.
  34. reader, _ = gzip.NewReader(bytes.NewReader(data))
  35. io.Copy(buffer, reader)
  36. output := self.addJavaScript(buffer.Bytes())
  37. reader.Close()
  38. buffer.Reset()
  39. // encode back to HTML with added javascript reference.
  40. writer := gzip.NewWriter(buffer)
  41. writer.Write(output)
  42. writer.Close()
  43. data = buffer.Bytes()
  44. } else if encoding == "deflate" {
  45. // decode to add javascript reference.
  46. reader, _ = zlib.NewReader(bytes.NewReader(data))
  47. io.Copy(buffer, reader)
  48. output := self.addJavaScript(buffer.Bytes())
  49. reader.Close()
  50. buffer.Reset()
  51. // encode back to HTML with added javascript reference.
  52. writer := zlib.NewWriter(buffer)
  53. writer.Write(output)
  54. writer.Close()
  55. data = buffer.Bytes()
  56. }
  57. }
  58. }
  59. return self.ResponseWriter.Write(data)
  60. }
  61. func Middleware(next http.Handler) http.Handler {
  62. // ONLY run this under debug mode.
  63. if !env.Bool("DEBUG") {
  64. return next
  65. }
  66. Start()
  67. fn := func(w http.ResponseWriter, r *http.Request) {
  68. if r.URL.Path == URL.WebSocket {
  69. ServeWebSocket(w, r)
  70. } else if r.URL.Path == URL.JavaScript {
  71. ServeJavaScript(w, r)
  72. } else {
  73. writer := &writer{w, r.Host}
  74. next.ServeHTTP(writer, r)
  75. }
  76. }
  77. return http.HandlerFunc(fn)
  78. }