Thursday, November 20, 2014

JSON RPC framework in 12 lines

There are lots of times when I just shake my head in admiration of what Groovy actually is. This has been one of the times today and I'm here to tell you I'm not easily impressed.

We're introducing a communication layer between our microservices based on JSON-RPC (just because it's cool and fast). Here's an initial implementation of a Groovy-based framework for doing JSON-RPC calls:

class JsonRpcClient extends HTTPBuilder {
    JsonRpcClient(String uri) {
        super(uri)
    }

    def methodMissing(String name, args) {
        def result
        request(POST, JSON) { req ->
            body = [ 
                "jsonrpc" : "2.0", 
                "method" : name, 
                "params" : args, "id" : 1 ]
            response.success = { resp, json ->  result = json }
        }
        return result
    }
}

I means sure it's not complete but using it is very much possible!

def http = new JsonRpcClient('http://localhost:8080/example/api/hello')
println http.sayHello("John")

I mean how cool is that, ha? Some meta programming with an existing framework (HTTPBuilder) and you get a micro implementation of JSON-RPC protocol in a few lines of code!

Happy coding! Groovy Rulez!

No comments: