LSP-server-example
107 строк · 2.7 Кб
1package server
2
3import (
4"encoding/json"
5"errors"
6)
7
8const protocolVersion = "2.0"
9
10type Message interface {
11IsJSONRPC() bool
12}
13
14type Request struct {
15ProtocolVersion string `json:"jsonrpc"`
16ID *json.RawMessage `json:"id"`
17Method string `json:"method"`
18Params json.RawMessage `json:"params"`
19}
20
21func (r Request) IsJSONRPC() bool {
22return r.ProtocolVersion == protocolVersion
23}
24
25func (r Request) IsNotification() bool {
26return r.ID == nil
27}
28
29type Response struct {
30ProtocolVersion string `json:"jsonrpc"`
31ID *json.RawMessage `json:"id"`
32Result any `json:"result"`
33Error *Error `json:"error"`
34}
35
36func (r Response) IsJSONRPC() bool {
37return r.ProtocolVersion == protocolVersion
38}
39
40type Error struct {
41// Code is a Number that indicates the error type that occurred.
42Code int64 `json:"code"`
43// Message of the error.
44// The message SHOULD be limited to a concise single sentence.
45Message string `json:"message"`
46// A Primitive or Structured value that contains additional information about the error.
47// This may be omitted.
48// The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).
49Data any `json:"data"`
50}
51
52func (e *Error) Error() string {
53return e.Message
54}
55
56var (
57ErrParseError = &Error{Code: -32700, Message: "Parse error"}
58ErrInvalidRequest = &Error{Code: -32600, Message: "Invalid Request"}
59ErrMethodNotFound = &Error{Code: -32601, Message: "Method not found"}
60ErrInvalidParams = &Error{Code: -32602, Message: "Invalid params"}
61ErrInternal = &Error{Code: -32603, Message: "Internal error"}
62ErrServerNotInitialized = &Error{Code: -32002, Message: "Server not initialized"}
63)
64var ErrInvalidContentLengthHeader = errors.New("missing or invalid Content-Length header")
65
66func NewResponseError(id *json.RawMessage, err error) Response {
67return Response{
68ProtocolVersion: protocolVersion,
69ID: id,
70Result: nil,
71Error: newError(err),
72}
73}
74
75func newError(err error) *Error {
76if err == nil {
77return nil
78}
79var e *Error
80if errors.As(err, &e) {
81return e
82}
83return &Error{
84Code: 0,
85Message: err.Error(),
86Data: nil,
87}
88}
89
90func NewResponse(id *json.RawMessage, result any) Response {
91return Response{
92ProtocolVersion: protocolVersion,
93ID: id,
94Result: result,
95Error: nil,
96}
97}
98
99type Notification struct {
100ProtocolVersion string `json:"jsonrpc"`
101Method string `json:"method"`
102Params any `json:"params"`
103}
104
105func (n Notification) IsJSONRPC() bool {
106return n.ProtocolVersion == protocolVersion
107}
108