|
| 1 | +package lsp |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "strconv" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +// Parse parses the content of a JSON-RPC message from r following the LSP specification |
| 13 | +// |
| 14 | +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#baseProtocol |
| 15 | +func Parse(r *bufio.Reader) ([]byte, error) { |
| 16 | + var contentLength int |
| 17 | + for { |
| 18 | + line, err := r.ReadString('\n') |
| 19 | + if err != nil { |
| 20 | + return nil, err |
| 21 | + } |
| 22 | + if !strings.HasSuffix(line, "\r\n") { |
| 23 | + return nil, fmt.Errorf(`line ending must be \r\n`) |
| 24 | + } |
| 25 | + line = strings.TrimSuffix(line, "\r\n") |
| 26 | + if line == "" { |
| 27 | + break |
| 28 | + } |
| 29 | + if value, ok := strings.CutPrefix(line, "Content-Length: "); ok { |
| 30 | + contentLength, err = strconv.Atoi(strings.TrimSpace(value)) |
| 31 | + if err != nil { |
| 32 | + return nil, fmt.Errorf("invalid Content-Length value: %w", err) |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + if contentLength == 0 { |
| 38 | + return nil, fmt.Errorf("no Content-Length header found") |
| 39 | + } |
| 40 | + |
| 41 | + buf := make([]byte, contentLength) |
| 42 | + _, err := io.ReadFull(r, buf) |
| 43 | + return buf, err |
| 44 | +} |
| 45 | + |
| 46 | +// Respond writes JSON data to w following the LSP specification |
| 47 | +// |
| 48 | +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#baseProtocol |
| 49 | +func Respond(w io.Writer, v any) error { |
| 50 | + data, err := json.Marshal(v) |
| 51 | + if err != nil { |
| 52 | + return err |
| 53 | + } |
| 54 | + if _, err := fmt.Fprintf(w, "Content-Length: %d\r\n\r\n", len(data)); err != nil { |
| 55 | + return err |
| 56 | + } |
| 57 | + if _, err := w.Write(data); err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + return nil |
| 61 | +} |
0 commit comments