shithub: hugo

ref: cd062623bd9eb1ded58b774086236ccc8130db8b
dir: /livereload/livereload.go/

View raw version
sed: Output line too long
// Copyright © 2014 Steve Francia <[email protected]>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package livereload

import (
	"net/http"
	"strings"

	"github.com/gorilla/websocket"
)

var upgrader = &websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024}

func Handler(w http.ResponseWriter, r *http.Request) {
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		return
	}
	c := &connection{send: make(chan []byte, 256), ws: ws}
	wsHub.register <- c
	defer func() { wsHub.unregister <- c }()
	go c.writer()
	c.reader()
}

func Initialize() {
	go wsHub.run()
}

func ForceRefresh() {
	// Tell livereload a js file changed to force a hard refresh
	RefreshPath("/x.js")
}

func RefreshPath(s string) {
	// Tell livereload a file has changed - will force a hard refresh if not CSS or an image
	urlPath := strings.Replace(s, "\\", "/", -1) // If path has backslashes on Windows, make path work for URL
	wsHub.broadcast <- []byte(`{"command":"reload","path":"` + urlPath + "\"" + `,"originalPath":"","liveCSS":true,"liveImg":true}`)
}

func ServeJS(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/javascript")
	w.Write(livereloadJS)
}