Twirp is a protocol for routing and serialization of services defined in a .proto
file, allowing easy implementation of RPC services with auto-generated clients in different languages.
Twirp-Ruby allows to define Twirp services and clients in Ruby.
Usage Example
Define the service and client using the DSL. This can be auto-generated from a .proto file.
module Example
class HelloWorldService < Twirp::Service
package "example"
service "HelloWorld"
rpc :Hello, HelloRequest, HelloResponse, :ruby_method => :hello
end
class HelloWorldClient < Twirp::Client
client_for HelloWorldService
end
end
Implement each RPC method with a Service Handler. For example:
class HelloWorldHandler
def hello(req, env)
if req.name.empty?
return Twirp::Error.invalid_argument("name is mandatory")
end
{message: "Hello #{req.name}"}
end
end
Service Handlers are just plain objects that respond to RPC methods with already serialized requests. Because of this they are very easy to unit test. Integration with Rack middleware can be done through service hooks, keeping the handler free of dependencies.
Use the client to talk to your service:
client = Example::HelloWorldClient.new("http://localhost:3000/twirp")
resp = client.hello(name: "World")
if resp.error
puts resp.error # <Twirp::Error code:... msg:"..." meta:{...}>
else
puts resp.data # <Example::HelloResponse: message:"Hello World">
end
Or debug using JSON from curl
:
curl --request POST \
--url http://localhost:3000/twirp/example.HelloWorld/Hello \
--header 'Content-Type: application/json' \
--data '{"name": "World"}'
You can auto-generate clients in other languages like Go, JavaScript, Python, Rust, etc. See the Twirp canonical implementation for more info.