diff --git a/README.md b/README.md index f2fbddd66d2d2c52b2741c424bc16fe7bf1b9801..9924fb547c93aec8e1141c8b9ec09269e248ac53 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,8 @@ go get nhooyr.io/websocket@v1.5.0 For a production quality example that shows off the full API, see the [echo example on the godoc](https://godoc.org/nhooyr.io/websocket#example-package--Echo). On github, the example is at [example_echo_test.go](./example_echo_test.go). +Please use the [golang.org/x/xerrors](https://godoc.org/golang.org/x/xerrors#As) package to check for [websocket.CloseError](https://godoc.org/nhooyr.io/websocket#CloseError). See the [CloseError godoc example](https://godoc.org/nhooyr.io/websocket#example-CloseError). + ### Server ```go diff --git a/example_test.go b/example_test.go index 22c3120285f47880dc399e10a91bbebff4be77b6..797658b47059e4e6ba152eebbfbe4972886fa253 100644 --- a/example_test.go +++ b/example_test.go @@ -6,6 +6,8 @@ import ( "net/http" "time" + "golang.org/x/xerrors" + "nhooyr.io/websocket" "nhooyr.io/websocket/wsjson" ) @@ -60,6 +62,26 @@ func ExampleDial() { c.Close(websocket.StatusNormalClosure, "") } +// This example dials a server and then expects to be disconnected with status code +// websocket.StatusNormalClosure. +func ExampleCloseError() { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + + c, _, err := websocket.Dial(ctx, "ws://localhost:8080", nil) + if err != nil { + log.Fatal(err) + } + defer c.Close(websocket.StatusInternalError, "the sky is falling") + + _, _, err = c.Reader(ctx) + var cerr websocket.CloseError + if !xerrors.As(err, &cerr) || cerr.Code != websocket.StatusNormalClosure { + log.Fatalf("expected to be disconnected with StatusNormalClosure but got: %+v", err) + return + } +} + // This example shows how to correctly handle a WebSocket connection // on which you will only write and do not expect to read data messages. func Example_writeOnly() {