Skip to content

Commit

Permalink
feat: json rpc serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
benpueschel committed Jun 30, 2024
1 parent 1ce087b commit bc8e228
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
42 changes: 42 additions & 0 deletions rpc/rpc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package rpc

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strconv"
)

func EncodeMessage(message any) string {
content, err := json.Marshal(message)
if err != nil {
panic(err)
}

return fmt.Sprintf("Content-Length: %d\r\n\r\n%s", len(content), content)
}

type BaseMessage struct {
Method string `json:"method"`
}

func DecodeMessage(msg []byte) (BaseMessage, []byte, error) {
header, content, found := bytes.Cut(msg, []byte{'\r', '\n', '\r', '\n'})
if !found {
return BaseMessage{}, nil, errors.New("No separator found")
}
contentLengthBytes := header[len("Content-Length: "):]
contentLength, err := strconv.Atoi(string(contentLengthBytes))
if err != nil {
return BaseMessage{}, nil, err
}
content = content[:contentLength]
var message BaseMessage
err = json.Unmarshal(content, &message)
if err != nil {
return message, nil, err
}

return message, content, nil
}
30 changes: 30 additions & 0 deletions rpc/rpc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package rpc_test

import (
"testing"
"github.com/benpueschel/conventional-commit-lsp/rpc"
)

type EncodingExample struct {
Method string `json:"method"`
}
var incommingMessage = "Content-Length: 15\r\n\r\n{\"method\":\"hi\"}"
func TestEncodeMessage(t *testing.T) {
actual := rpc.EncodeMessage(EncodingExample{Method: "hi"})
if incommingMessage != actual {
t.Fatalf("Expected %s, got %s", incommingMessage, actual)
}
}

func TestDecodeMessage(t *testing.T) {
message, content, err := rpc.DecodeMessage([]byte(incommingMessage))
if err != nil {
t.Fatalf("Error decoding message: %s", err)
}
if message.Method != "hi" {
t.Fatalf("Expected %s, got %s", "hi", message.Method)
}
if len(content) != 15 {
t.Fatalf("Expected %d, got %d", 15, len(content))
}
}

0 comments on commit bc8e228

Please sign in to comment.