Skip to content

Commit

Permalink
refactor: choose writer in main
Browse files Browse the repository at this point in the history
- Created function writeResponse to automatically encode an rpc message
  and write it to the specified io.Writer
- Added variable `writer` in main to increase flexibility. This allows
  us to implement custom writers to communicate with the client.
  • Loading branch information
benpueschel committed Jun 30, 2024
1 parent 06a265a commit e46a4f9
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"bytes"
"encoding/json"
"io"
"log"
"os"
"strconv"
Expand All @@ -20,6 +21,7 @@ func main() {
scanner.Split(Split)

state := analysis.NewState()
writer := os.Stdout

for scanner.Scan() {
msg := scanner.Bytes()
Expand All @@ -28,11 +30,11 @@ func main() {
logger.Printf("Failed to decode message: %s", err)
continue
}
handleMessage(logger, &state, message, contents)
handleMessage(logger, writer, &state, message, contents)
}
}

func handleMessage(logger *log.Logger, state *analysis.State, msg rpc.BaseMessage, contents []byte) {
func handleMessage(logger *log.Logger, writer io.Writer, state *analysis.State, msg rpc.BaseMessage, contents []byte) {
logger.Printf("Received message with method: %s", msg.Method)

switch msg.Method {
Expand All @@ -45,9 +47,7 @@ func handleMessage(logger *log.Logger, state *analysis.State, msg rpc.BaseMessag
logger.Printf("Connected to client: %s %s", request.Params.ClientInfo.Name, request.Params.ClientInfo.Version)

msg := lsp.NewInitializeResponse(request.ID)
reply := rpc.EncodeMessage(msg)
writer := os.Stdout
writer.Write([]byte(reply))
writeResponse(msg, writer)
logger.Println("Sent initialize response")
case "textDocument/didOpen":
var request lsp.TextDocumentDidOpenNotification
Expand All @@ -70,6 +70,11 @@ func handleMessage(logger *log.Logger, state *analysis.State, msg rpc.BaseMessag
}
}

func writeResponse(msg any, writer io.Writer) {
reply := rpc.EncodeMessage(msg)
writer.Write([]byte(reply))
}

func getLogger(filename string) *log.Logger {
file, err := os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
if err != nil {
Expand Down

0 comments on commit e46a4f9

Please sign in to comment.