A habit-tracking gRPC service needs an agreement about what clients send and receive. Protocol Buffers (Protobuf) provides that agreement in language-neutral .proto files: messages define structured data, and service declarations define endpoints. gRPC carries the encoded messages over HTTP/2. section 10.1
Start a .proto file with `syntax = "proto3";` and a package declaration. Add `option go_package` when generating Go code. Each message field has a type, name, and unique number. Keep an existing field’s number fixed: later versions rely on that number to recognize the field. section 10.1.1
Listing 10.3 habit.proto: Defining the Habit message
// Habit represents an objective one wants to complete
// a given number of times per week.
message Habit { #1
// Name of the habit, cannot be empty
string name = 1; #2
// Frequency, expressed in times per week.
int32 weekly_frequency = 2;
}
The Habit message assigns field 1 to its name and field 2 to its weekly frequency. Its comments describe the contract for people using the generated code. section 10.1.1
Define operations separately from the data they manage. A `Habits` service can declare `CreateHabit` with its own request and response messages; the response can contain a `Habit`. The API can also expose operations to list habits, record a tick, and retrieve status. The .proto declarations can then be compiled to generate Go interfaces and structures. section 10.1.1 section 10.8
Listing 10.6 service.proto: Request and response
import "habit.proto"; #1
service Habits {
...
}
// CreateHabitRequest is the message sent to create a habit.
message CreateHabitRequest {
// Name of the new habit. Cannot be empty.
string name = 1;
// Frequency of the new habit. Will default to once per week.
optional int32 weekly_frequency = 2; #2
}
// CreateHabitResponse is the response of the create endpoint.
message CreateHabitResponse {
Habit habit = 1;
}
The CreateHabit contract imports the Habit definition, declares the request fields, and places a Habit in the response. The weekly-frequency field is marked optional. section 10.1.1
To try the endpoint manually, start the Go server and call `habits.Habits/CreateHabit` with grpcurl. Supply `service.proto` through `-proto` and its import root through `-import-path`; grpcurl accepts a human-readable JSON request using those definitions. Unlike a JSON API tested with curl, a Protobuf message needs its schema to be interpreted. Server reflection is another way to provide that definition, but it is not used here. section 10.3.2 section 10.8
> grpcurl \
-import-path /.../learngo-pockets/habits/api/proto/ \ #1
-proto service.proto \ #2
-plaintext -d '{"name":"clean the kitchen"}' \ #3
localhost:28710 \ #4
habits.Habits/CreateHabit #5
The command shows the schema path, plaintext local connection, JSON request, and fully qualified endpoint for a manual CreateHabit call. section 10.3.2









