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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. )
  12. type writer struct {
  13. http.ResponseWriter
  14. host string
  15. }
  16. func (self *writer) addJavaScript(data []byte) []byte {
  17. javascript := fmt.Sprintf(`<script defer src="//%s%s"></script>
  18. </head>`, self.host, URL.JavaScript)
  19. return regexp.MustCompile(`</head>`).ReplaceAll(data, []byte(javascript))
  20. }
  21. func (self *writer) Write(data []byte) (size int, e error) {
  22. if strings.Contains(self.Header().Get("Content-Type"), "html") {
  23. var encoding = self.Header().Get("Content-Encoding")
  24. if encoding == "" {
  25. data = self.addJavaScript(data)
  26. } else {
  27. var reader io.ReadCloser
  28. var buffer *bytes.Buffer = new(bytes.Buffer)
  29. if encoding == "gzip" {
  30. // decode to add javascript reference.
  31. reader, _ = gzip.NewReader(bytes.NewReader(data))
  32. io.Copy(buffer, reader)
  33. output := self.addJavaScript(buffer.Bytes())
  34. reader.Close()
  35. buffer.Reset()
  36. // encode back to HTML with added javascript reference.
  37. writer := gzip.NewWriter(buffer)
  38. writer.Write(output)
  39. writer.Close()
  40. data = buffer.Bytes()
  41. } else if encoding == "deflate" {
  42. // decode to add javascript reference.
  43. reader, _ = zlib.NewReader(bytes.NewReader(data))
  44. io.Copy(buffer, reader)
  45. output := self.addJavaScript(buffer.Bytes())
  46. reader.Close()
  47. buffer.Reset()
  48. // encode back to HTML with added javascript reference.
  49. writer := zlib.NewWriter(buffer)
  50. writer.Write(output)
  51. writer.Close()
  52. data = buffer.Bytes()
  53. }
  54. }
  55. }
  56. return self.ResponseWriter.Write(data)
  57. }
  58. func Middleware(next http.Handler) http.Handler {
  59. Start()
  60. fn := func(w http.ResponseWriter, r *http.Request) {
  61. if r.URL.Path == URL.WebSocket {
  62. ServeWebSocket(w, r)
  63. } else if r.URL.Path == URL.JavaScript {
  64. ServeJavaScript(w, r)
  65. } else {
  66. writer := &writer{w, r.Host}
  67. next.ServeHTTP(writer, r)
  68. }
  69. }
  70. return http.HandlerFunc(fn)
  71. }