CloseWithJSON cleanly closes the underlying WebSocket connection by sending given object (marshaled using json.Marshal()) as a close message and then waiting (with timeout) for the server to close the connection. WebSocket close code may be optionally specified. If not, then "1000 - Normal Closure"
(
object interface{}, code ...int,
)
| 330 | // conn := resp.Connection() |
| 331 | // conn.CloseWithJSON(MyJSON{Foo: 123}, websocket.CloseUnsupportedData) |
| 332 | func (ws *Websocket) CloseWithJSON( |
| 333 | object interface{}, code ...int, |
| 334 | ) *Websocket { |
| 335 | opChain := ws.chain.enter("CloseWithJSON()") |
| 336 | defer opChain.leave() |
| 337 | |
| 338 | switch { |
| 339 | case ws.checkUnusable(opChain, "CloseWithJSON()"): |
| 340 | return ws |
| 341 | |
| 342 | case len(code) > 1: |
| 343 | opChain.fail(AssertionFailure{ |
| 344 | Type: AssertUsage, |
| 345 | Errors: []error{ |
| 346 | errors.New("unexpected multiple code arguments"), |
| 347 | }, |
| 348 | }) |
| 349 | return ws |
| 350 | } |
| 351 | |
| 352 | b, err := json.Marshal(object) |
| 353 | |
| 354 | if err != nil { |
| 355 | opChain.fail(AssertionFailure{ |
| 356 | Type: AssertValid, |
| 357 | Actual: &AssertionValue{object}, |
| 358 | Errors: []error{ |
| 359 | errors.New("invalid json object"), |
| 360 | err, |
| 361 | }, |
| 362 | }) |
| 363 | return ws |
| 364 | } |
| 365 | |
| 366 | ws.writeMessage(opChain, websocket.CloseMessage, b, code...) |
| 367 | |
| 368 | return ws |
| 369 | } |
| 370 | |
| 371 | // CloseWithText cleanly closes the underlying WebSocket connection |
| 372 | // by sending given text as a close message and then waiting (with timeout) |