• Stars
    star
    511
  • Rank 86,473 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated almost 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⚡🐦 Elegant WebSockets in Go

Thunderbird - Elegant WebSockets in Go

I'm competing at Gopher Gala 2016. Please give this project a star and follow me if you like what you see 🍻.

Thunderbird (a.k.a. 🐦) seamlessly integrates WebSockets with your Go web application. It allows for real-time features to be written in idiomatic Go. It's a full-stack offering that provides both a client-side JavaScript framework and a server-side Go framework. Thunderbird is heavily inspired by Elixir's Phoenix and Rails' Action Cable.

How it works

Thunderbird is built around the concept of connections and channels. It has one connection per WebSocket connection. A single user may have multiple WebSockets open to your application if they use multiple browser tabs or devices. The client of a WebSocket connection is called a consumer and it can subscribe to multiple channels. Each channel responds to a name and encapsulates a logical unit of work similar to a controller in a regular MVC setup. Just like how pub/sub works, a broadcast can be made to consumers that subscribed to a channel.

Here is an example of multiple channels on multiple connections:

          ┌──────────┐
          │          │           Connection1
          │ Client1  │◀──────[channel1, channel2]────────┐
          │          │                                   │
          └──────────┘                                   ▼
                                                ┌────────────────┐
                          Connection2           │                │
                ┌─────[channel2, channel3]─────▶│     Server     │
                │                               │                │
                ▼                               └────────────────┘
          ┌──────────┐                                   ▲
          │          │           Connection3             │
          │ Client2  │◀───────────[channel3]─────────────┘
          │          │
          └──────────┘

Tutorial: a chat app

Let's walk through building a chat app with Thunderbird and understand how elegant the solution is. The code is available in the example folder. The example is running live here.

Server handling WebSocket connections

The first thing is to initialize Thunderbird and create a route to handle WebSocket connections:

func main() {
  tb := thunderbird.New()

  mux := http.NewServeMux()
  mux.Handle("/ws", tb.HTTPHandler())
}

Thunderbird.HTTPHandler() returns a http.Handler that deals with WebSocket connections.

Server handling a channel

We then create a channel handler that implements the ChannelHandler interface. ChannelHandlers are registered with Thunderbird.HandleChannel which takes a name and a ChannelHandler:

type RoomChannel struct {
}

func (rc *RoomChannel) Received(event thunderbird.Event) {
    // handle event
}

func main() {
    ch := &RoomChannel{}
    tb.HandleChannel("room", ch)
}

Server broadcasting messages to consumers

For a chat app, we want RoomChannel to broadcast received messages to all consumers of the channel. We do this by calling Thunderbird.Broadcast when there is a message event:

type RoomChannel struct {
    tb *thunderbird.Thunderbird
}

func (rc *RoomChannel) Received(event thunderbird.Event) {
    switch event.Type {
    case "message":
      rc.tb.Broadcast(event.Channel, event.Body)
    }
}

Event.Type represents the type of the event received. Currently the value can be subscribed, unsubscribed or message which mean a subscription was made to the channel, a unsubscription was made to channel or a message was received on the channel correspondingly. More event types will be support in the future.

So far the Go side of the chat app is done. That was easy, right :-)? Let's take a look at the JavaScript part of the app.

Client connecting

On the client, we call Thunderbird.connect to connect to the Go server. The method takes a URL and a callback that accepts a connection object. In thie case url should be the WebSocket URL that we set up in previous step: ws://localhost:8080/ws.

Thunderbird.connect(url, function (conn) {
  // do something with the connection `conn`
})

Client subscribing to a channel

With the conn, we can subscribe to a channel (room in our example) and do something with the received message in the callback:

conn.subscribe("room", function (msg) {
  // handle message
})

Client sending messages

For a chat app, we would like to send messages to other consumers and we do that with the perform method of the connection:

// when enter key is pressed
conn.perform("room", msg)

### Client's host is different than server

If client is hosted on another server than Thunderbird runs, most likely they have different hostnames.
In such a case, you should use Thunderbird.HTTPHandlerWithUpgrader() and define your custom Origin header validator.

func main() {
  tb := thunderbird.New()
  tbUpgrader := websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    CheckOrigin: func(r *http.Request) bool {
      return true
    },
  }

  mux := http.NewServeMux()
  mux.Handle("/ws", tb.HTTPHandlerWithUpgrader(tbUpgrader))
}

Roadmap

Thunderbird is under heavy development. Please be patient before it hits prime time :-).

  • WebSocket HTTP handler
  • Basic in memory pub/sub
  • JavaScript client
  • Example chat app
  • Redis pub/sub adapter
  • Postgres pub/sub adapter

LICENSE

See LICENSE.md.

More Repositories

1

ccat

Colorizing `cat`
Go
3,105
star
2

godzilla

Godzilla is a ES2015 to Go source code transpiler and runtime
Go
1,482
star
3

hacker-menu

Hacker News Delivered to Desktop 👯
JavaScript
1,004
star
4

upterm

Instant Terminal Sharing
Go
838
star
5

jqplay

A playground for jq, written in Go
Go
724
star
6

gh

Fast GitHub command line client (deprecated). gh has been merged into https://github.com/github/hub, see https://github.com/github/hub/issues/475 for more info
Go
721
star
7

goup

Elegant Go installer
Go
478
star
8

spotctl

A command-line interface to Spotify, written in Go
Go
242
star
9

nut

Vendor Go dependencies
Go
234
star
10

gotask

Idiomatic build tool in Go
Go
177
star
11

jekyll_and_hyde

A HTML presentation generator that generates a basic Jekyll scaffold with Slippy hooking up.
Ruby
174
star
12

candy

Candy is a zero-config reverse proxy server
Go
119
star
13

devise_uid

Add UID support to Devise.
Ruby
61
star
14

gaffer

Gaffer - Foreman on JVM
Java
56
star
15

msgpack_rails

MessagePack for Rails / msgpack.org[Rails]
Ruby
45
star
16

conf

Configuration loader in Go
Go
31
star
17

negroni-gorelic

negroni_gorelic is NewRelic middleware for negroni framework.
Go
27
star
18

gundam

The most destructive robot
Go
18
star
19

sql_parser

A Ruby SQL parser based on Treetop.
Ruby
18
star
20

vimux-zeus

vimux and zeus in action.
Vim Script
14
star
21

go-get-nuts

HTML5 Game built with Phaser
JavaScript
10
star
22

heroic_haiku

A simple game that is written in Flutter and Flame.
Dart
10
star
23

heroku-buildpack-wasmer

Heroku Buildpack for Wasmer
Shell
8
star
24

osh

The O shell
Go
8
star
25

jruby_sinatra_activerecord

A template app to run JRuby with Sinatra and ActiveRecord
Ruby
7
star
26

travisarchive

Travis Archive
Go
7
star
27

blog

My blog
JavaScript
6
star
28

dotfiles_old

My dotfiles
Shell
6
star
29

git-rebase-merge

A bash script to rebase and merge a Git topic branch to current branch.
Shell
5
star
30

homebrew-ccat

Homebrew fomular for `ccat` (deprecated), use `brew install ccat` instead
Ruby
4
star
31

eventloopclass

Go version of the exercises for The Truth About Event Loop Online Masterclass
Go
4
star
32

message_queue

A common interface to multiple message queues libraries.
Ruby
4
star
33

codeface

Run web-based VS Code on Heroku
Go
3
star
34

cheatsheets

3
star
35

patching_with_class_shadowing_and_maven

Using Maven to help with class shadowing.
Java
3
star
36

codefaces

a web-based source control client
Java
3
star
37

dotfiles

My dotfiles
Shell
3
star
38

hdp

HTTP Debug Proxy (HDP) logs HTTP requests for inspection.
Go
3
star
39

com.google.dart.compiler

A Dart compiler implemented in Java extracted from Dart's official repository.
Java
3
star
40

maven_jetty_plugin_example

Speed Up J2EE Environment Setup With Jetty Maven Plugin Example
Java
2
star
41

.dotfiles

dotfiles for my Mac
Ruby
2
star
42

mag

MAG - Full-Stack application development using MongoDB, AngularJS, and Go
2
star
43

ruby_grep

Module to search file(s) for lines that match a given pattern.
Ruby
2
star
44

priority_test

Run tests in priority order.
Ruby
2
star
45

tic_tac_toe_engine

A dead simple Tic Tac Toe engine.
Ruby
2
star
46

homebrew-gh

GH formulae for the Homebrew package manager
Ruby
2
star
47

testing_rest_web_services_with_rails

Ruby
2
star
48

rbfmt

Format Ruby code
Ruby
2
star
49

StoryboardRecipes

Example app following the book "iOS SDK Development" from Pragmatic Programmer
Objective-C
2
star
50

gostart

Go
1
star
51

buildzilla

Ruby
1
star
52

twitter_plus

an example of my talk about testing web service client
Ruby
1
star
53

isittheday.com

Ruby
1
star
54

stats_foundry

Ruby
1
star
55

ijws

I Just Wanna Say
Ruby
1
star
56

jekyll_and_hyde_demo

An example presentation generated by jekyll_and_hyde
1
star
57

karotz-proxy

Ruby
1
star
58

rails_engines_spike

Ruby
1
star
59

vpm

An awesome utility for managing Vim plugins.
Ruby
1
star
60

heroku-nginx-wasmer

Run Nginx with Wasmer on Heroku
HTML
1
star
61

api-proxy-spike

A spike to implement an API proxy
JavaScript
1
star
62

automatic_testing_of_rest_web_sevices_client_with_rails_source

Ruby
1
star
63

cortana

A Hubot for Twitter
CoffeeScript
1
star
64

odt

Owen's Development Tool
Go
1
star
65

rab

Rails Asset Builder (RAB)
Ruby
1
star
66

summarize-github-pull-requests

Perform automatic code reviews for GitHub pull requests (PR). The review is triggered when a PR is created and is triggered again for every subsequent commit in the PR. The code review is conducted for commit in the PR.
Rust
1
star
67

shortenerclj

A URL shortener implemented in Clojure
Clojure
1
star
68

hurley

Hurley and Faraday are both from the lost island
Go
1
star
69

sinatra-jruby-heroku

Shell
1
star
70

gameserverstatus

gameserverstatus
Clojure
1
star
71

narc

Node.js CI Server
JavaScript
1
star
72

jekyll_and_hyde_template

The source of the default jekyll_and_hyde template used by its generator.
1
star
73

loading_path_gotchas_in_rails3

A gotchas on load path of Rails 3.
Ruby
1
star
74

testing_web_services_client_slides

JavaScript
1
star