readJSONRPCResponse reads lines from the scanner, skipping server-initiated notifications (messages without an "id" field), and returns the first response.
(scanner *bufio.Scanner)
| 487 | // readJSONRPCResponse reads lines from the scanner, skipping server-initiated |
| 488 | // notifications (messages without an "id" field), and returns the first response. |
| 489 | func readJSONRPCResponse(scanner *bufio.Scanner) (string, error) { |
| 490 | for scanner.Scan() { |
| 491 | line := scanner.Text() |
| 492 | // JSON-RPC responses have an "id" field; notifications do not. |
| 493 | var msg map[string]json.RawMessage |
| 494 | if err := json.Unmarshal([]byte(line), &msg); err != nil { |
| 495 | return "", fmt.Errorf("failed to parse JSON-RPC message: %w", err) |
| 496 | } |
| 497 | if _, hasID := msg["id"]; hasID { |
| 498 | if errField, hasErr := msg["error"]; hasErr { |
| 499 | return "", fmt.Errorf("server returned error: %s", string(errField)) |
| 500 | } |
| 501 | return line, nil |
| 502 | } |
| 503 | // No "id" — this is a notification, skip it |
| 504 | } |
| 505 | if err := scanner.Err(); err != nil { |
| 506 | return "", err |
| 507 | } |
| 508 | return "", fmt.Errorf("unexpected end of output") |
| 509 | } |
| 510 | |
| 511 | func printResponse(response string, prettyPrint bool) error { |
| 512 | if !prettyPrint { |
no outgoing calls