-
-
Notifications
You must be signed in to change notification settings - Fork 113
Writing Schemas and Generating Code
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. Compiler plugins exist for most major languages.
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.
❗Before you begin❗
Ensure your shell's
$PATH
variable includes$GOPATH/bin
. Ask us for help if you're stuck.
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$GOPATH/src/capnproto.org/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
.
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 Go code, you should learn how to marshal and unmarshal them.