From 2d41f39727d868d6d577a8705432f4563fb00a41 Mon Sep 17 00:00:00 2001 From: Anmol Sethi <hi@nhooyr.io> Date: Mon, 2 Sep 2019 17:28:02 -0500 Subject: [PATCH] Add a CloseError example Closes #128 --- README.md | 2 ++ example_test.go | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/README.md b/README.md index f2fbddd..9924fb5 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 22c3120..797658b 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() { -- GitLab