tliron / glsp

Language Server Protocol SDK for Go
Apache License 2.0
149 stars 21 forks source link

feat(protocol): Add custom request handling #32

Open tris203 opened 2 weeks ago

tris203 commented 2 weeks ago

This commit introduces the ability to handle custom requests in the protocol package. A new struct, CustomRequestHandler, has been added which contains a Method and a Func. The Func is a function that takes a context and params and returns an error.

The Handler struct now includes a slice of CustomRequestHandlers, and the Handle method has been updated to handle custom requests by unmarshalling the params into the handler's params and then calling the handler's Func.

A new method, FindCustomRequestHandler, has been added to the Handler struct. This method takes a method string and returns the corresponding CustomRequestHandler and a boolean indicating whether the handler was found.

The server's handle method has also been updated to handle errors from the Handler's Handle method.

Usage example:

    CustomRequests := []protocol.CustomRequestHandler{
        {
            Func:   server.TestHandler,
            Method: "test/test",
        },
    }

    handler = protocol.Handler{
        Initialize:            server.initialize,
        Initialized:           server.initialized,
        Shutdown:              server.shutdown,
        SetTrace:              server.setTrace,
        TextDocumentDidOpen:   server.didOpen,
        TextDocumentDidChange: server.didChange,
        TextDocumentDidClose:  server.didClose,
        CustomRequest:         CustomRequests,
    }

then server.TestHandler as below:


func (s *Server) TestHandler(context *glsp.Context, params json.RawMessage) error {
    type TestParams struct {
        Nah string `json:"nah"`
    }

    unmarshaledParams := TestParams{}
    unmarshalErr := json.Unmarshal(params, &unmarshaledParams)
    if unmarshalErr != nil {
        fmt.Println("Error unmarshaling params")
    }
    fmt.Println("TestHandler")
    fmt.Printf("Params: %v", unmarshaledParams.Nah)
    return nil
}

Closes #31

tris203 commented 2 weeks ago

The only problem at the moment, is that because the params are private, it cause issues in the 317 library version as it gets confused over the version, but if i use the 316 version I cant access the params field I have made the Params field public, although I dont like it. I cant think of a better solution. Any suggestions on the most go like way of solving this?

tris203 commented 2 weeks ago

Also seeing this when there are custom routes implemented, I will investigate tomorrow

exit log ``` 2024/06/28 23:45:03 jsonrpc2 handler: notification "exit" handling error: server not initialized ```

this is due to now returning the error in server/handler.go as the exit notifcation comes after the shutdown and resolved in latest commits