processMessage processes a single message and calls a handler or callback.
(data []byte)
| 485 | |
| 486 | // processMessage processes a single message and calls a handler or callback. |
| 487 | func (c *Client) processMessage(data []byte) (msg *dnode.Message, fn interface{}, err error) { |
| 488 | // Call error handler. |
| 489 | defer func() { |
| 490 | if err != nil { |
| 491 | onError(err) |
| 492 | } |
| 493 | }() |
| 494 | |
| 495 | msg = &dnode.Message{} |
| 496 | |
| 497 | if err = json.Unmarshal(data, &msg); err != nil { |
| 498 | return nil, nil, err |
| 499 | } |
| 500 | |
| 501 | sender := func(id uint64, args []interface{}) error { |
| 502 | // do not name the error variable to "err" here, it's a trap for |
| 503 | // shadowing variables |
| 504 | _, _, e := c.marshalAndSend(id, args) |
| 505 | return e |
| 506 | } |
| 507 | |
| 508 | // Replace function placeholders with real functions. |
| 509 | if err := dnode.ParseCallbacks(msg, sender); err != nil { |
| 510 | return nil, nil, err |
| 511 | } |
| 512 | |
| 513 | // Find the handler function. Method may be string or integer. |
| 514 | switch method := msg.Method.(type) { |
| 515 | case float64: |
| 516 | id := uint64(method) |
| 517 | callback := c.scrubber.GetCallback(id) |
| 518 | if callback == nil { |
| 519 | err = dnode.CallbackNotFoundError{ |
| 520 | ID: id, |
| 521 | Args: msg.Arguments, |
| 522 | } |
| 523 | return nil, nil, err |
| 524 | } |
| 525 | |
| 526 | return msg, callback, nil |
| 527 | case string: |
| 528 | m, ok := c.LocalKite.handlers[method] |
| 529 | if !ok { |
| 530 | err = dnode.MethodNotFoundError{ |
| 531 | Method: method, |
| 532 | Args: msg.Arguments, |
| 533 | } |
| 534 | return nil, nil, err |
| 535 | } |
| 536 | |
| 537 | return msg, m, nil |
| 538 | default: |
| 539 | return nil, nil, fmt.Errorf("Method is not string or integer: %+v (%T)", msg.Method, msg.Method) |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | func (c *Client) Close() { |
| 544 | if !atomic.CompareAndSwapInt32(&c.closed, 0, 1) { |
no test coverage detected