Setting Up

Let’s start by initializing a new Go module for our project:

  1. mkdir ent-grpc-example
  2. cd ent-grpc-example
  3. go mod init ent-grpc-example

Next, we use go run to invoke the ent code generator to initialize a schema:

  1. go run -mod=mod entgo.io/ent/cmd/ent new User

Our directory should now look like:

  1. .
  2. ├── ent
  3. ├── generate.go
  4. └── schema
  5. └── user.go
  6. ├── go.mod
  7. └── go.sum

Next, let’s add the entproto package to our project:

  1. go get -u entgo.io/contrib/entproto

Next, we will define the schema for the User entity. Open ent/schema/user.go and edit:

ent/schema/user.go

  1. package schema
  2. import (
  3. "entgo.io/ent"
  4. "entgo.io/ent/schema/field"
  5. )
  6. // User holds the schema definition for the User entity.
  7. type User struct {
  8. ent.Schema
  9. }
  10. // Fields of the User.
  11. func (User) Fields() []ent.Field {
  12. return []ent.Field{
  13. field.String("name").
  14. Unique(),
  15. field.String("email_address").
  16. Unique(),
  17. }
  18. }

In this step, we added two unique fields to our User entity: name and email_address. The ent.Schema is just the definition of the schema. To create usable production code from it we need to run Ent’s code generation tool on it. Run:

  1. go generate ./...

Notice that new files were created from our schema definition:

  1. ├── ent
  2. ├── client.go
  3. ├── config.go
  4. // .... many more
  5. ├── user
  6. ├── user.go
  7. ├── user_create.go
  8. ├── user_delete.go
  9. ├── user_query.go
  10. └── user_update.go
  11. ├── go.mod
  12. └── go.sum

At this point, we can open a connection to a database, run a migration to create the users table, and start reading and writing data to it. This is covered on the Setup Tutorial, so let’s cut to the chase and learn about generating Protobuf definitions and gRPC servers from our schema.