ref: 7e08d23eebe8de8c688150900423dca6234b22a8
parent: 0ce6438268961b76d11ef6e9210b03c2100171b1
author: Dragos Plesca <[email protected]>
date: Thu Jun 16 15:43:47 EDT 2016
transform: Explicitly bind LiveReload to server port If hugo server is run on port 80 or 443, LiveReload does not correctly bind to the same port, instead using port 35729. This commit adds functionality to inform LiveReload of the correct port to bind to. See https://github.com/livereload/livereload-js/issues/16 Partially contributed by Jeff Minard (@chuyskywalker). Fixes #2205
--- a/transform/livereloadinject.go
+++ b/transform/livereloadinject.go
@@ -16,18 +16,21 @@
import (
"bytes"
"fmt"
+
+ "github.com/spf13/viper"
)
func LiveReloadInject(ct contentTransformer) {
endBodyTag := "</body>"
match := []byte(endBodyTag)
- replaceTemplate := `<script data-no-instant>document.write('<script src="/livereload.js?mindelay=10"></' + 'script>')</script>%s`
- replace := []byte(fmt.Sprintf(replaceTemplate, endBodyTag))
+ port := viper.Get("port")
+ replaceTemplate := `<script data-no-instant>document.write('<script src="/livereload.js?port=%d&mindelay=10"></' + 'script>')</script>%s`
+ replace := []byte(fmt.Sprintf(replaceTemplate, port, endBodyTag))
newcontent := bytes.Replace(ct.Content(), match, replace, 1)
if len(newcontent) == len(ct.Content()) {
endBodyTag = "</BODY>"
- replace := []byte(fmt.Sprintf(replaceTemplate, endBodyTag))
+ replace := []byte(fmt.Sprintf(replaceTemplate, port, endBodyTag))
match := []byte(endBodyTag)
newcontent = bytes.Replace(ct.Content(), match, replace, 1)
}
--- a/transform/livereloadinject_test.go
+++ b/transform/livereloadinject_test.go
@@ -18,6 +18,8 @@
"fmt"
"strings"
"testing"
+
+ "github.com/spf13/viper"
)
func TestLiveReloadInject(t *testing.T) {
@@ -26,6 +28,7 @@
}
func doTestLiveReloadInject(t *testing.T, bodyEndTag string) {
+ viper.Set("port", 1313)
out := new(bytes.Buffer)
in := strings.NewReader(bodyEndTag)
@@ -32,7 +35,7 @@
tr := NewChain(LiveReloadInject)
tr.Apply(out, in, []byte("path"))
- expected := fmt.Sprintf(`<script data-no-instant>document.write('<script src="/livereload.js?mindelay=10"></' + 'script>')</script>%s`, bodyEndTag)
+ expected := fmt.Sprintf(`<script data-no-instant>document.write('<script src="/livereload.js?port=1313&mindelay=10"></' + 'script>')</script>%s`, bodyEndTag)
if string(out.Bytes()) != expected {
t.Errorf("Expected %s got %s", expected, string(out.Bytes()))
}