Scalar Types
- double64-bit float
- float32-bit float
- int32/int64Signed integers
- uint32/uint64Unsigned ints
- boolBoolean
- stringUTF-8 text
- bytesBinary data
RPC Types
- UnaryRequest/response
- Server streamingOne req, many resp
- Client streamingMany req, one resp
- BidirectionalMany both ways
Field Rules
- optionalMay be unset
- repeatedList of values
- map<K,V>Key-value pairs
- oneofOne of fields
- reservedReserved numbers
Status Codes
- OKSuccess
- INVALID_ARGUMENTBad input
- NOT_FOUNDResource missing
- UNAUTHENTICATEDNo auth
- PERMISSION_DENIEDNo access
- INTERNALServer error
Proto3 Message Definition
syntax = "proto3";
package user.v1;
option go_package = "github.com/example/user/v1";
message User {
int64 id = 1;
string name = 2;
string email = 3;
UserStatus status = 4;
repeated string roles = 5;
map<string, string> metadata = 6;
}
enum UserStatus {
USER_STATUS_UNSPECIFIED = 0;
USER_STATUS_ACTIVE = 1;
USER_STATUS_INACTIVE = 2;
}
Service Definition
service UserService {
// Unary RPC
rpc GetUser(GetUserRequest) returns (User);
// Server streaming
rpc ListUsers(ListUsersRequest) returns (stream User);
// Client streaming
rpc CreateUsers(stream CreateUserRequest) returns (CreateUsersResponse);
// Bidirectional streaming
rpc Chat(stream ChatMessage) returns (stream ChatMessage);
}
message GetUserRequest {
int64 id = 1;
}
grpcurl Commands
# List services
grpcurl -plaintext \
localhost:50051 list
# Describe service
grpcurl -plaintext \
localhost:50051 describe \
user.v1.UserService
# Call RPC
grpcurl -plaintext \
-d '{"id": 1}' \
localhost:50051 \
user.v1.UserService/GetUser
Code Generation
# Install protoc plugins
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
# Generate Go code
protoc --go_out=. \
--go-grpc_out=. \
proto/user.proto
# Buf generate
buf generate
Go Client Example
import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "github.com/example/user/v1"
)
// Create connection
conn, err := grpc.Dial(
"localhost:50051",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
defer conn.Close()
// Create client
client := pb.NewUserServiceClient(conn)
// Make RPC call
resp, err := client.GetUser(ctx, &pb.GetUserRequest{Id: 1})
Go Server Example
type server struct {
pb.UnimplementedUserServiceServer
}
func (s *server) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.User, error) {
// Implementation
return &pb.User{Id: req.Id, Name: "Alice"}, nil
}
func main() {
lis, _ := net.Listen("tcp", ":50051")
s := grpc.NewServer()
pb.RegisterUserServiceServer(s, &server{})
s.Serve(lis)
}
Well-Known Types
- TimestampDate/time
- DurationTime span
- EmptyNo data
- AnyDynamic type
- StructJSON-like
Metadata
- AuthorizationAuth tokens
- x-request-idRequest tracing
- grpc-timeoutDeadline
- content-typeapplication/grpc