API Definition

Kratos implements REST and gRPC as the transport protocols. We mainly follow the API Design Guide from Google.

You could define REST API and gRPC API in proto files and generate Go codes from these files.

API Definition

You could define REST API and gRPC API in Protobuf IDL.

api/helloworld/v1/greeter.proto

  1. syntax = "proto3";
  2. package helloworld.v1;
  3. import "google/api/annotations.proto";
  4. option go_package = "github.com/go-kratos/service-layout/api/helloworld/v1;v1";
  5. option java_multiple_files = true;
  6. option java_package = "dev.kratos.api.helloworld.v1";
  7. option java_outer_classname = "HelloWorldProtoV1";
  8. // The greeting service definition.
  9. service Greeter {
  10. // Sends a greeting
  11. rpc SayHello (HelloRequest) returns (HelloReply) {
  12. option (google.api.http) = {
  13. // To define GET API, map name to HelloRequest
  14. get: "/helloworld/{name}",
  15. // You could also add some additional APIs
  16. additional_bindings {
  17. // To define POST API, map body to HelloRequest
  18. post: "/v1/greeter/say_hello",
  19. body: "*",
  20. }
  21. };
  22. }
  23. }
  24. // The request message contains the user's name.
  25. message HelloRequest {
  26. string name = 1;
  27. }
  28. // The response message contains the greetings
  29. message HelloReply {
  30. string message = 1;
  31. }

API Generation

  1. # To generate proto template
  2. kratos proto add api/helloworld/v1/greeter.proto
  3. # To generate client codes
  4. kratos proto client api/helloworld/v1/greeter.proto
  5. # To generate server codes
  6. kratos proto server api/helloworld/v1/greeter.proto -t internal/service
  1. client:
  2. |____api
  3. | |____helloworld
  4. | | |____v1
  5. | | | |____greeter.pb.go
  6. | | | |____greeter.proto
  7. | | | |____greeter_http.pb.go
  8. | | | |____greeter_grpc.pb.go
  9. server:
  10. | |____service
  11. | | |____greeter.go

API Register

HTTP API is an http.Handler, which is generated by protoc-gen-go-http plugin, can be registered into HTTP Server.

  1. import "github.com/go-kratos/kratos/v2/transport/http"
  2. greeter := &GreeterService{}
  3. srv := http.NewServer(http.Address(":8000"))
  4. srv.HandlePrefix("/", v1.NewGreeterHandler(greeter))

gRPC API is a gRPC Register, which is generated by protoc-gen-go-grpc plugin, can be registered into GRPC Server.

  1. import "github.com/go-kratos/kratos/v2/transport/grpc"
  2. greeter := &GreeterService{}
  3. srv := grpc.NewServer(grpc.Address(":9000"))
  4. v1.RegisterGreeterServer(srv, greeter)

References