0Pricing
Go Academy · Lesson

Using gorilla/websocket

Upgrade and handle connections.

Using gorilla/websocket is a free Go Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The gorilla/websocket Library

gorilla/websocket is the most widely used Go WebSocket library. It handles the upgrade handshake and gives you a connection object to read and write frames. Install with go get github.com/gorilla/websocket.

import "github.com/gorilla/websocket"

The Upgrader

An Upgrader turns an HTTP request into a WebSocket connection. You configure buffer sizes and an origin check.

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

CheckOrigin and Security

By default the Upgrader rejects cross-origin requests. During development you may relax it, but in production validate the Origin header to prevent cross-site WebSocket hijacking.

upgrader.CheckOrigin = func(r *http.Request) bool {
    return r.Header.Get("Origin") == "https://myapp.com"
}

Upgrading in a Handler

Inside an http.HandlerFunc, call Upgrade. On success you get a *websocket.Conn.

func wsHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        return
    }
    defer conn.Close()
    // read/write loop here
}

Reading Messages

ReadMessage blocks until a frame arrives, returning the message type and payload bytes.

mt, data, err := conn.ReadMessage()
if err != nil {
    return // client closed or error
}
fmt.Printf("got %d bytes\n", len(data))
_ = mt

Writing Messages

WriteMessage sends a frame of a given type:

err := conn.WriteMessage(websocket.TextMessage, []byte("hello"))
if err != nil {
    return
}

The Echo Loop

A classic example reads a message and writes it back. The loop ends when Read returns an error (the client disconnected).

for {
    mt, msg, err := conn.ReadMessage()
    if err != nil {
        break
    }
    conn.WriteMessage(mt, msg)
}

JSON Helpers

gorilla provides ReadJSON and WriteJSON to marshal Go values directly over the socket, which is handy for structured messages. The Msg struct field carries a json:"text" tag in real source.

type Msg struct {
    Text string // tag: json text
}
var m Msg
conn.ReadJSON(&m)
conn.WriteJSON(Msg{Text: "ack"})

One Reader, One Writer Rule

Important: a single connection allows only one concurrent reader and one concurrent writer. If multiple goroutines write, guard with a mutex or funnel writes through one goroutine (covered in broadcasting).

Registering the Route

Wire the handler like any HTTP route. Clients connect to ws://host/ws.

http.HandleFunc("/ws", wsHandler)
http.ListenAndServe(":8080", nil)

Runnable: JSON Round-Trip Analogy

WebSocket code needs the external library; this standard-library snippet mirrors ReadJSON/WriteJSON by unmarshaling an incoming message into a map and marshaling a reply.

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    in := []byte("{\"text\":\"ping\"}")
    var m map[string]string
    json.Unmarshal(in, &m)
    reply, _ := json.Marshal(map[string]string{"text": m["text"] + "-ack"})
    fmt.Println(string(reply))
}

Quick Check

Test your understanding of gorilla/websocket usage.

Recap

You learned to use gorilla/websocket:

  • An Upgrader performs the handshake; validate CheckOrigin
  • Upgrade yields a *websocket.Conn
  • Use ReadMessage/WriteMessage or the JSON helpers
  • One reader and one writer per connection at a time

Frequently asked questions

Is the “Using gorilla/websocket” lesson free?

Yes — the full text of “Using gorilla/websocket” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Using gorilla/websocket”?

Upgrade and handle connections. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Using gorilla/websocket” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. WebSocket Basics
  2. Using gorilla/websocket
  3. Broadcasting Messages
  4. Connection Management
← Back to Go Academy