Cap'n Proto works by generating code. First, you create a schema using Cap'n Proto's interface-definition language (IDL). Then, you feed this schema into the Cap'n Proto compiler, which generates the corresponding code in your native language.
There is support for other languages, too.
Ensure that you have installed the capnp
compiler and the Go language plugin, and that your shell's $PATH
variable includes $GOPATH/bin
.
Refer to the previous section for instructions.
Consider the following schema, stored in foo/books.capnp
:
using Go = import "/go.capnp";
@0x85d3acc39d94e0f8;
$Go.package("books");
$Go.import("foo/books");
struct Book {
title @0 :Text;
# Title of the book.
pageCount @1 :Int32;
# Number of pages in the book.
}
capnpc-go requires that two annotations be present in your schema:
$Go.package("books")
: tells the compiler to placepackage books
at the top of the generated Go files.$Go.import("foo/books")
: declares the full import path within your project. The compiler uses this to generate the import statement in the auto-generated code, when one of your schemas imports a type from another.
Compilation will fail unless these annotations are present.
To compile this schema into Go code, run the following command. Note that the source path /foo/books.capnp
must correspond to the import path declared in your annotations.
capnp compile -I /path/to/go-capnp/std -ogo foo/books.capnp
Tip 👉 For more compilation options, see
capnp compile --help
.
This will output the foo/books.capnp.go
file, containing Go structs that can be imported into your programs. These are ordinary Go types that represent the schema you declared in books.capnp
. Each has accessor methods corresponding to the fields declared in the schema. For example, the Book
struct will have the methods Title() (string, error)
and SetTitle(string) error
.
If you have go-capnp as a dependency and you are in go module folder, you can use go list
and backticks like so
capnp compile -I `go list -m -f '{{.Dir}}' capnproto.org/go/capnp/v3`/std -ogo foo/books.capnp
In the next section, we will show how you can write these structs to a file or transmit them over the network.
Now that you have generated code from your schema, you should learn how to work with Cap'n Proto types.