mirror of
https://github.com/42wim/matterbridge.git
synced 2024-11-29 07:29:29 +01:00
.. | ||
.gitignore | ||
CHANGELOG.md | ||
config.go | ||
doc.go | ||
envelope.go | ||
errors.go | ||
hub.go | ||
LICENSE | ||
melody.go | ||
README.md | ||
session.go |
melody
🎶 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
Example: chat
package main
import (
"net/http"
"github.com/olahol/melody"
)
func main() {
:= melody.New()
m
.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
http})
.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
http.HandleRequest(w, r)
m})
.HandleMessage(func(s *melody.Session, msg []byte) {
m.Broadcast(msg)
m})
.ListenAndServe(":5000", nil)
http}
Example: gophers
package main
import (
"net/http"
"strings"
"github.com/google/uuid"
"github.com/olahol/melody"
)
type GopherInfo struct {
, X, Y string
ID}
func main() {
:= melody.New()
m
.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
http})
.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
http.HandleRequest(w, r)
m})
.HandleConnect(func(s *melody.Session) {
m, _ := m.Sessions()
ss
for _, o := range ss {
, exists := o.Get("info")
value
if !exists {
continue
}
:= value.(*GopherInfo)
info
.Write([]byte("set " + info.ID + " " + info.X + " " + info.Y))
s}
:= uuid.NewString()
id .Set("info", &GopherInfo{id, "0", "0"})
s
.Write([]byte("iam " + id))
s})
.HandleDisconnect(func(s *melody.Session) {
m, exists := s.Get("info")
value
if !exists {
return
}
:= value.(*GopherInfo)
info
.BroadcastOthers([]byte("dis "+info.ID), s)
m})
.HandleMessage(func(s *melody.Session, msg []byte) {
m:= strings.Split(string(msg), " ")
p , exists := s.Get("info")
value
if len(p) != 2 || !exists {
return
}
:= value.(*GopherInfo)
info .X = p[0]
info.Y = p[1]
info
.BroadcastOthers([]byte("set "+info.ID+" "+info.X+" "+info.Y), s)
m})
.ListenAndServe(":5000", nil)
http}
More examples
Documentation
Contributors
FAQ
If you are getting a 403
when trying to connect to your
websocket you can change
allow all origin hosts:
:= melody.New()
m .Upgrader.CheckOrigin = func(r *http.Request) bool { return true } m