Skip to content

Commit

Permalink
Bind livereload to the same port as hugo
Browse files Browse the repository at this point in the history
If hugo is run with port 80 or 443, live reload 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.

Fixes gohugoio#2205
  • Loading branch information
chuyskywalker committed Jun 24, 2016
1 parent 2564f46 commit 31fea04
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
10 changes: 7 additions & 3 deletions transform/livereloadinject.go
Expand Up @@ -16,18 +16,22 @@ package transform
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)
}
Expand Down
5 changes: 4 additions & 1 deletion transform/livereloadinject_test.go
Expand Up @@ -17,6 +17,7 @@ import (
"bytes"
"fmt"
"github.com/spf13/hugo/helpers"
"github.com/spf13/viper"
"testing"
)

Expand All @@ -26,13 +27,15 @@ func TestLiveReloadInject(t *testing.T) {
}

func doTestLiveReloadInject(t *testing.T, bodyEndTag string) {
viper.Set("port", 1313)

out := new(bytes.Buffer)
in := helpers.StringToReader(bodyEndTag)

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()))
}
Expand Down

0 comments on commit 31fea04

Please sign in to comment.