...

Source file src/github.com/gorilla/websocket/examples/echo/server.go

Documentation: github.com/gorilla/websocket/examples/echo

     1  // Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build ignore
     6  // +build ignore
     7  
     8  package main
     9  
    10  import (
    11  	"flag"
    12  	"html/template"
    13  	"log"
    14  	"net/http"
    15  
    16  	"github.com/gorilla/websocket"
    17  )
    18  
    19  var addr = flag.String("addr", "localhost:8080", "http service address")
    20  
    21  var upgrader = websocket.Upgrader{} // use default options
    22  
    23  func echo(w http.ResponseWriter, r *http.Request) {
    24  	c, err := upgrader.Upgrade(w, r, nil)
    25  	if err != nil {
    26  		log.Print("upgrade:", err)
    27  		return
    28  	}
    29  	defer c.Close()
    30  	for {
    31  		mt, message, err := c.ReadMessage()
    32  		if err != nil {
    33  			log.Println("read:", err)
    34  			break
    35  		}
    36  		log.Printf("recv: %s", message)
    37  		err = c.WriteMessage(mt, message)
    38  		if err != nil {
    39  			log.Println("write:", err)
    40  			break
    41  		}
    42  	}
    43  }
    44  
    45  func home(w http.ResponseWriter, r *http.Request) {
    46  	homeTemplate.Execute(w, "ws://"+r.Host+"/echo")
    47  }
    48  
    49  func main() {
    50  	flag.Parse()
    51  	log.SetFlags(0)
    52  	http.HandleFunc("/echo", echo)
    53  	http.HandleFunc("/", home)
    54  	log.Fatal(http.ListenAndServe(*addr, nil))
    55  }
    56  
    57  var homeTemplate = template.Must(template.New("").Parse(`
    58  <!DOCTYPE html>
    59  <html>
    60  <head>
    61  <meta charset="utf-8">
    62  <script>  
    63  window.addEventListener("load", function(evt) {
    64  
    65      var output = document.getElementById("output");
    66      var input = document.getElementById("input");
    67      var ws;
    68  
    69      var print = function(message) {
    70          var d = document.createElement("div");
    71          d.textContent = message;
    72          output.appendChild(d);
    73          output.scroll(0, output.scrollHeight);
    74      };
    75  
    76      document.getElementById("open").onclick = function(evt) {
    77          if (ws) {
    78              return false;
    79          }
    80          ws = new WebSocket("{{.}}");
    81          ws.onopen = function(evt) {
    82              print("OPEN");
    83          }
    84          ws.onclose = function(evt) {
    85              print("CLOSE");
    86              ws = null;
    87          }
    88          ws.onmessage = function(evt) {
    89              print("RESPONSE: " + evt.data);
    90          }
    91          ws.onerror = function(evt) {
    92              print("ERROR: " + evt.data);
    93          }
    94          return false;
    95      };
    96  
    97      document.getElementById("send").onclick = function(evt) {
    98          if (!ws) {
    99              return false;
   100          }
   101          print("SEND: " + input.value);
   102          ws.send(input.value);
   103          return false;
   104      };
   105  
   106      document.getElementById("close").onclick = function(evt) {
   107          if (!ws) {
   108              return false;
   109          }
   110          ws.close();
   111          return false;
   112      };
   113  
   114  });
   115  </script>
   116  </head>
   117  <body>
   118  <table>
   119  <tr><td valign="top" width="50%">
   120  <p>Click "Open" to create a connection to the server, 
   121  "Send" to send a message to the server and "Close" to close the connection. 
   122  You can change the message and send multiple times.
   123  <p>
   124  <form>
   125  <button id="open">Open</button>
   126  <button id="close">Close</button>
   127  <p><input id="input" type="text" value="Hello world!">
   128  <button id="send">Send</button>
   129  </form>
   130  </td><td valign="top" width="50%">
   131  <div id="output" style="max-height: 70vh;overflow-y: scroll;"></div>
   132  </td></tr></table>
   133  </body>
   134  </html>
   135  `))
   136  

View as plain text