Skip to main content

API

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.

Definition#

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

api/helloworld/v1/greeter.proto

syntax = "proto3";
package helloworld.v1;
import "google/api/annotations.proto";
option go_package = "github.com/go-kratos/service-layout/api/helloworld/v1;v1";option java_multiple_files = true;option java_package = "dev.kratos.api.helloworld.v1";option java_outer_classname = "HelloWorldProtoV1";
// The greeting service definition.service Greeter {  // Sends a greeting  rpc SayHello (HelloRequest) returns (HelloReply)  {    option (google.api.http) = {        // To define GET API, map name to HelloRequest        get: "/helloworld/{name}",        // You could also add some additional APIs        additional_bindings {            // To define POST API, map body to HelloRequest            post: "/v1/greeter/say_hello",            body: "*",        }    };  }}
// The request message contains the user's name.message HelloRequest {  string name = 1;}
// The response message contains the greetingsmessage HelloReply {  string message = 1;}

Generation#

# To generate proto templatekratos proto add api/helloworld/v1/greeter.proto# To generate client codeskratos proto client api/helloworld/v1/greeter.proto# To generate server codeskratos proto server api/helloworld/v1/greeter.proto -t internal/service
client:|____api| |____helloworld| | |____v1| | | |____greeter.pb.go| | | |____greeter.proto| | | |____greeter_http.pb.go| | | |____greeter_grpc.pb.go
server:| |____service| | |____greeter.go

Register API#

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

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

gRPC API is gRPC Registrar which generated by protoc-gen-go-grpc plugin, can be registered into GRPCServer.

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

References#