protocol.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package lsp
  2. import (
  3. "encoding/json"
  4. )
  5. // Message represents a JSON-RPC 2.0 message
  6. type Message struct {
  7. JSONRPC string `json:"jsonrpc"`
  8. ID int32 `json:"id,omitempty"`
  9. Method string `json:"method,omitempty"`
  10. Params json.RawMessage `json:"params,omitempty"`
  11. Result json.RawMessage `json:"result,omitempty"`
  12. Error *ResponseError `json:"error,omitempty"`
  13. }
  14. // ResponseError represents a JSON-RPC 2.0 error
  15. type ResponseError struct {
  16. Code int `json:"code"`
  17. Message string `json:"message"`
  18. }
  19. func NewRequest(id int32, method string, params any) (*Message, error) {
  20. paramsJSON, err := json.Marshal(params)
  21. if err != nil {
  22. return nil, err
  23. }
  24. return &Message{
  25. JSONRPC: "2.0",
  26. ID: id,
  27. Method: method,
  28. Params: paramsJSON,
  29. }, nil
  30. }
  31. func NewNotification(method string, params any) (*Message, error) {
  32. paramsJSON, err := json.Marshal(params)
  33. if err != nil {
  34. return nil, err
  35. }
  36. return &Message{
  37. JSONRPC: "2.0",
  38. Method: method,
  39. Params: paramsJSON,
  40. }, nil
  41. }