Go Academy · Lesson

Using gorilla/websocket

Upgrade and handle connections.

Lesson 2 of 413 steps

Using gorilla/websocket is a free Go Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

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
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Using gorilla/websocket” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “Using gorilla/websocket”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

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