Gorilla Websockets, golang simple websockets example

I previously posted a quick example of using the standard library websockets API in golang. Unfortunately there are a number of issues that make difficult to use in practice. Notably, it lacks support for PING/PONG packets which are often used to for KeepAlive functionality in websockets. This is particularly important, as browsers tend to be aggressive in killing off these connections.

So, here’s a quick complete example of Gorilla Websockets in golang, with similar functionality to that I posted previously. It simply echos everything it receives back to the client. First the golang code:

package main

import (

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

func print_binary(s []byte) {
  fmt.Printf("Received b:");
  for n := 0;n < len(s);n++ {

func echoHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {

    for {
        messageType, p, err := conn.ReadMessage()
        if err != nil {


        err = conn.WriteMessage(messageType, p);
        if  err != nil {

func main() {
  http.HandleFunc("/echo", echoHandler)
  http.Handle("/", http.FileServer(http.Dir(".")))
  err := http.ListenAndServe(":8080", nil)
  if err != nil {
    panic("Error: " + err.Error())

And then the html used to interface with the websocket. Save it in the same directory as the golang program, and access it at: http://localhost:8080/filename.html

<meta charset="UTF-8" />
        var serversocket = new WebSocket("ws://localhost:8080/echo");

        serversocket.onopen = function() {
                serversocket.send("Connection init");

        // Write message on receive
        serversocket.onmessage = function(e) {
                document.getElementById('comms').innerHTML += "Received: " + e.data + "<br>";

        function senddata() {
                var data = document.getElementById('sendtext').value;
                document.getElementById('comms').innerHTML += "Sent: " + data + "<br>";


        <input id="sendtext" type="text" />
        <input type="button" id="sendBtn" value="send" onclick="senddata()"></input>
        <div id='comms'></div>

Comments are closed.