Repository navigation
gRPC
Tuntii edited this page Dec 3, 2026
·
1 revision
A gRPC call is an HTTP/2 POST to /<package>.<Service>/<Method> with content-type: application/grpc. The
body is one length-prefixed message, and the call's status goes out as a trailer field after the response
body. Viltrum serves that with an ordinary route: c.body() holds the request message, c.set_trailer sets
grpc-status, and c.bytes sends the reply. There is no gRPC or protobuf library in V and viltrum does not add
one: the handler reads and writes the protobuf fields itself.
import viltrum
fn main() {
mut app := viltrum.new()
app.post('/helloworld.Greeter/SayHello', say_hello)
app.serve([
viltrum.Listener{
addr: '0.0.0.0:50051'
http2: true // cleartext h2c: gRPC clients speak HTTP/2 with prior knowledge
},
])!
}
fn say_hello(mut c viltrum.Ctx) {
b := c.body()
// a gRPC message: a compressed flag byte, a 4-byte big-endian length, the protobuf bytes
if b.len < 5 || b[0] != 0 {
c.set_trailer('grpc-status', '13') // INTERNAL
c.bytes(200, 'application/grpc', []u8{})
return
}
request := b[5..] // HelloRequest, protobuf-encoded
reply := encode_hello_reply(request) // your protobuf code: framed the same way, 5-byte prefix first
c.set_trailer('grpc-status', '0')
c.bytes(200, 'application/grpc', reply)
}A complete handler, with the varint reading and writing and the error statuses, is the HttpArena entry's
GetSum: benches/httparena/grpc.v.
Over TLS, add tls: viltrum.TlsOptions{...} to the listener: gRPC clients agree on h2 by ALPN
(TLS).
- Answer HTTP status 200 even when the call fails: gRPC carries its own status in
grpc-status(0OK,3INVALID_ARGUMENT,12UNIMPLEMENTED,13INTERNAL, ...). An optionalgrpc-messagetrailer carries the error text. - Set the trailers before
c.bytes: they go out in a HEADERS frame after the last DATA frame. Up to 4 trailer fields per response. - An empty reply body is valid for a failed call.
| Streaming RPCs (client, server or bidirectional) | trailers are not sent after a streaming response (c.stream) |
Compressed messages (grpc-encoding) |
answer 12 UNIMPLEMENTED when the flag byte is not 0 |
| gRPC over HTTP/1.1 or HTTP/3 | trailer fields go out over HTTP/2 only (HTTP/3) |
Deadlines (grpc-timeout) |
the header reaches the handler (c.header); acting on it is up to you |
| Reflection, health checking, protobuf code generation | not part of viltrum |