• Stars
    star
    3,473
  • Rank 12,254 (Top 0.3 %)
  • Language
    Go
  • License
    BSD 2-Clause "Sim...
  • Created almost 9 years ago
  • Updated about 2 months ago

Reviews

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

Repository Details

🎶 Minimalist websocket framework for Go

melody

Build Status Codecov Go Report Card GoDoc

🎶 Minimalist websocket framework for Go.

Melody is websocket framework based on github.com/gorilla/websocket that abstracts away the tedious parts of handling websockets. It gets out of your way so you can write real-time apps. Features include:

  • Clear and easy interface similar to net/http or Gin.
  • A simple way to broadcast to all or selected connected sessions.
  • Message buffers making concurrent writing safe.
  • Automatic handling of sending ping/pong heartbeats that timeout broken sessions.
  • Store data on sessions.

Install

go get github.com/olahol/melody

Chat

package main

import (
	"net/http"

	"github.com/olahol/melody"
)

func main() {
	m := melody.New()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "index.html")
	})

	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		m.HandleRequest(w, r)
	})

	m.HandleMessage(func(s *melody.Session, msg []byte) {
		m.Broadcast(msg)
	})

	http.ListenAndServe(":5000", nil)
}

Gophers

package main

import (
	"net/http"
	"strings"

	"github.com/google/uuid"
	"github.com/olahol/melody"
)

type GopherInfo struct {
	ID, X, Y string
}

func main() {
	m := melody.New()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "index.html")
	})

	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		m.HandleRequest(w, r)
	})

	m.HandleConnect(func(s *melody.Session) {
		ss, _ := m.Sessions()

		for _, o := range ss {
			value, exists := o.Get("info")

			if !exists {
				continue
			}

			info := value.(*GopherInfo)

			s.Write([]byte("set " + info.ID + " " + info.X + " " + info.Y))
		}

		id := uuid.NewString()
		s.Set("info", &GopherInfo{id, "0", "0"})

		s.Write([]byte("iam " + id))
	})

	m.HandleDisconnect(func(s *melody.Session) {
		value, exists := s.Get("info")

		if !exists {
			return
		}

		info := value.(*GopherInfo)

		m.BroadcastOthers([]byte("dis "+info.ID), s)
	})

	m.HandleMessage(func(s *melody.Session, msg []byte) {
		p := strings.Split(string(msg), " ")
		value, exists := s.Get("info")

		if len(p) != 2 || !exists {
			return
		}

		info := value.(*GopherInfo)
		info.X = p[0]
		info.Y = p[1]

		m.BroadcastOthers([]byte("set "+info.ID+" "+info.X+" "+info.Y), s)
	})

	http.ListenAndServe(":5000", nil)
}

Contributors

FAQ

If you are getting a 403 when trying to connect to your websocket you can change allow all origin hosts:

m := melody.New()
m.Upgrader.CheckOrigin = func(r *http.Request) bool { return true }

More Repositories

1

react-tagsinput

Highly customizable React component for inputing tags.
JavaScript
1,342
star
2

reactpack

📦 build your react apps with one command and one `npm i`.
JavaScript
982
star
3

melody-jsnes

📺 Multiplayer NES through the magic of WebSockets and Go.
HTML
768
star
4

react-ab

Simple declarative and universal A/B testing component for React.
JavaScript
430
star
5

react-social

Simple React components for social buttons (Facebook, Twitter and Pinterest) and social counts.
HTML
177
star
6

go-imageupload

🔳 Gracefully handle image uploading and thumbnail creation.
Go
138
star
7

iso-3166-2.js

Lookup information about ISO-3166-2 subdivisions
JavaScript
106
star
8

express-chrome-logger

Debug your express app using the Chrome console.
JavaScript
84
star
9

pocketplace

🎆 Draw pixels on a canvas with friends.
Go
80
star
10

scrollparent.js

A function to get the scrolling parent of a html element.
HTML
58
star
11

node-csp

Communicating sequential processes for node.
JavaScript
55
star
12

iso-3166-2.json

JSON file of ISO 3166-2 subdivisions.
JavaScript
55
star
13

greasyphone

📱 🎮 Play NES using smartphones as joypads
JavaScript
45
star
14

viewdiff

📒 view your diffs in a separate window.
JavaScript
41
star
15

bf2c

🐛 Not the smallest compiler ever
JavaScript
20
star
16

socialcount.js

Tiny javascript library for getting social share counts. Pinterest, Facebook, Twitter and Google Plus supported.
JavaScript
17
star
17

ethereum-web1-guestbook

📓 A Web 1.0 guestbook on Web 3.0
HTML
15
star
18

cpp-csp

Minimalistic header-only library for channels and CSP (Communicating sequential process) in C++11.
C++
14
star
19

mainthread

Run functions in Go's main thread.
Go
14
star
20

eselement

DOM-like wrapper around the Javascript AST
JavaScript
6
star
21

tsreflect

Flexible reflection based TypeScript type generator for Go types that can be marshalled with `encoding/json`.
Go
6
star
22

capreq

Capture HTTP Requests using gopacket and libpcap
Go
6
star
23

hnplain

output Hacker News in plain text
Python
6
star
24

react-bus

Event emitter designed for communication between react components.
JavaScript
5
star
25

bf2asmjs

A simple brainfuck compiler targeting asm.js
Python
5
star
26

spawn.js

Tiny javascript library for spinning up one off web workers.
JavaScript
3
star
27

node-crcaptcha

Node package for using the Civil Rights Captcha.
JavaScript
2
star
28

tiny-xss-scanner

Lighweight xss scanner
Python
2
star
29

olapass

Stateless password manager.
JavaScript
1
star
30

request-animation-loop

As setInterval is to setTimeout, requestAnimationLoop is to requestAnimationFrame.
JavaScript
1
star
31

cpp-project-template

A small template for C++11 projects using tup and clang.
C++
1
star
32

generator-react-umd

A Yeoman generator that generates a minimalistic scaffold for a ES6 React component wrapped with the UMD.
JavaScript
1
star
33

gin-csrf

CSRF protection middleware for Go web framework Gin
Go
1
star
34

node-mysql-slowlog

Application level slow log for mysql connections. Good for debugging slow queries when you haven't turned on or have access to the database slow log.
JavaScript
1
star