Skip to content

Repository files navigation

websocket

godocci

websocket is a minimal and idiomatic WebSocket library for Go.

This is a fork of nhooyr.io/websocket with a few major changes

  • not usable from wasm/js
  • stripped down go.mod
  • removed wspb package
  • meant for server-side usage only

Install

go get github.com/fortytw2/websocket

Highlights

Roadmap

  • HTTP/2 #4

Examples

For a production quality example that demonstrates the complete API, see the echo example.

For a full stack example, see the chat example.

Server

http.HandlerFunc(func (w http.ResponseWriter, r*http.Request) {
c, err:=websocket.Accept(w, r, nil)
iferr!=nil {
// ...
}
deferc.Close(websocket.StatusInternalError, "the sky is falling")
ctx, cancel:=context.WithTimeout(r.Context(), time.Second*10)
defercancel()
varvinterface{}
err=wsjson.Read(ctx, c, &v)
iferr!=nil {
// ...
}
log.Printf("received: %v", v)
c.Close(websocket.StatusNormalClosure, "")
})

Client

ctx, cancel:=context.WithTimeout(context.Background(), time.Minute)
defercancel()
c, _, err:=websocket.Dial(ctx, "ws://localhost:8080", nil)
iferr!=nil {
// ...
}
deferc.Close(websocket.StatusInternalError, "the sky is falling")
err=wsjson.Write(ctx, c, "hi")
iferr!=nil {
// ...
}
c.Close(websocket.StatusNormalClosure, "")

Comparison

gorilla/websocket

Advantages of gorilla/websocket:

Advantages of github.com/fortytw2/websocket:

golang.org/x/net/websocket

golang.org/x/net/websocket is deprecated. See golang/go/issues/18152.

The net.Conn can help in transitioning to github.com/fortytw2/websocket.

gobwas/ws

gobwas/ws has an extremely flexible API that allows it to be used in an event driven style for performance. See the author's blog post.

However when writing idiomatic Go, github.com/fortytw2/websocket will be faster and easier to use.

About

independent fork of nhooyr.io/websocket

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages