Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

🎶 Minimalist websocket framework for Go

License

NotificationsYou must be signed in to change notification settings

olahol/melody

Repository files navigation

Build StatusCodecovGo Report CardGoDoc

🎶 Minimalist websocket framework for Go.

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

  • Clear and easy interface similar tonet/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 mainimport ("net/http""github.com/olahol/melody")funcmain() {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 mainimport ("fmt""net/http""sync/atomic""github.com/olahol/melody")varidCounter atomic.Int64funcmain() {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) {id:=idCounter.Add(1)s.Set("id",id)s.Write([]byte(fmt.Sprintf("iam %d",id)))})m.HandleDisconnect(func(s*melody.Session) {ifid,ok:=s.Get("id");ok {m.BroadcastOthers([]byte(fmt.Sprintf("dis %d",id)),s)}})m.HandleMessage(func(s*melody.Session,msg []byte) {ifid,ok:=s.Get("id");ok {m.BroadcastOthers([]byte(fmt.Sprintf("set %d %s",id,msg)),s)}})http.ListenAndServe(":5000",nil)}

Contributors

FAQ

If you are getting a403 when trying to connect to your websocket you canchange allow all origin hosts:

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

[8]ページ先頭

©2009-2025 Movatter.jp