github.com/shohhei1126/hugo@v0.42.2-0.20180623210752-3d5928889ad7/livereload/connection.go (about)

     1  // Copyright 2015 The Hugo Authors. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package livereload
    15  
    16  import (
    17  	"bytes"
    18  	"sync"
    19  
    20  	"github.com/gorilla/websocket"
    21  )
    22  
    23  type connection struct {
    24  	// The websocket connection.
    25  	ws *websocket.Conn
    26  
    27  	// Buffered channel of outbound messages.
    28  	send chan []byte
    29  
    30  	// There is a potential data race, especially visible with large files.
    31  	// This is protected by synchronisation of the send channel's close.
    32  	closer sync.Once
    33  }
    34  
    35  func (c *connection) close() {
    36  	c.closer.Do(func() {
    37  		close(c.send)
    38  	})
    39  }
    40  
    41  func (c *connection) reader() {
    42  	for {
    43  		_, message, err := c.ws.ReadMessage()
    44  		if err != nil {
    45  			break
    46  		}
    47  		if bytes.Contains(message, []byte(`"command":"hello"`)) {
    48  			c.send <- []byte(`{
    49  				"command": "hello",
    50  				"protocols": [ "http://livereload.com/protocols/official-7" ],
    51  				"serverName": "Hugo"
    52  			}`)
    53  		}
    54  	}
    55  	c.ws.Close()
    56  }
    57  
    58  func (c *connection) writer() {
    59  	for message := range c.send {
    60  		err := c.ws.WriteMessage(websocket.TextMessage, message)
    61  		if err != nil {
    62  			break
    63  		}
    64  	}
    65  	c.ws.Close()
    66  }