summaryrefslogtreecommitdiffstats
path: root/transform/livereloadinject.go
blob: eb431f14a35cf4cc59f798336d7c5aabc3024dac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package transform

import (
	"bytes"
	jww "github.com/spf13/jwalterweatherman"
	"github.com/spf13/viper"
)

func LiveReloadInject(content []byte) (injected []byte) {
	defer func() {
		if r := recover(); r != nil {
			jww.ERROR.Println("Recovered in LiveReloadInject", r)
			injected = content
		}
	}()
	match := []byte("</body>")
	port := viper.GetString("port")
	replace := []byte(`<script>document.write('<script src="http://'
        + (location.host || 'localhost').split(':')[0]
		+ ':` + port + `/livereload.js?mindelay=10"></'
        + 'script>')</script></body>`)
	newcontent := bytes.Replace(content, match, replace, -1)

	if len(newcontent) == len(content) {
		match := []byte("</BODY>")
		newcontent = bytes.Replace(content, match, replace, -1)
	}

	return newcontent
}