Kratos is a set of lightweight Go microservices framework, including a number of microservices related frameworks and tools.

The name comes from: “God of War” game is based on the background of Greek mythology, tells the story of Kratos, who becomes the god of war from a mortal and starts the adventure of killing god and killing god.

Tool set

kratos

The main commands of the kratos command line tool are

  • New (Create a project from the Layout template)
  • Proto (the proto command is used to define generated code through proto)
  • Upgrade (Upgrade Kratos and other accompanying command-line tools)

proto-gen-go-http

The proto-gen-go-http command line tool is used to generate HTTP code through proto definitions

service BlogService {
    rpc CreateArticle (CreateArticleRequest) returns (CreateArticleReply) {
        option (google.api.http) = {
            post: "/v1/article/"
            body: "*"
        };
    }
    rpc UpdateArticle (UpdateArticleRequest) returns (UpdateArticleReply) {
        option (google.api.http) = {
            put: "/v1/article/{id}"
            body: "*"
        };
    }
    rpc DeleteArticle (DeleteArticleRequest) returns (DeleteArticleReply) {
        option (google.api.http) = {
            delete: "/v1/article/{id}"
        };
    }
    rpc GetArticle (GetArticleRequest) returns (GetArticleReply) {
        option (google.api.http) = {
            get: "/v1/article/{id}"}; }}Copy the code

proto-gen-go-errors

The proto-gen-go-errors command line tool is used to generate errors code through proto definitions

enum ErrorReason {
  option (errors.default_code) = 500;
  USER_NOT_FOUND = 0 [(errors.code) = 500];
  CONTENT_MISSING = 1 [(errors.code) = 400];
}
Copy the code

proto-gen-validate

The proto-gen-go-errors command line tool is used to generate validate codes from proto definitions

message Request {
    int64 id = 1 [(validate.rules).int64 = {gt: 0}];
    int32 age = 2 [(validate.rules).int32 = {gt:0, lt: 120}];
    uint32 code = 3 [(validate.rules).uint32 = {in: [1.2.3]}];
    float score = 4 [(validate.rules).float = {not_in: [0.99.99]}];
    bool state = 5 [(validate.rules).bool.const = true];
    string path = 6 [(validate.rules).string.const = "/hello"];
    string phone = 7 [(validate.rules).string.len = 11];
    string explain = 8 [(validate.rules).string.min_len = 3];
    string name = 9 [(validate.rules).string = {min_len: 1, max_len: 10}];
    string card = 10 [(validate.rules).string.pattern = "(? i)^[0-9a-f]+$"];
    Info info = 11 [(validate.rules).message.required = true];
}
Copy the code

Makefile

Makefile and Kratos command line tools have basically the same functions and are easier to customize. (The following code applies to Makefile commands mentioned in this article, which is different from layout. Please note that.)

GOPATH:=$(shell go env GOPATH)
VERSION=$(shell git describe --tags --always)
INTERNAL_PROTO_FILES=$(shell find internal -name *.proto)
API_PROTO_FILES=$(shell find api -name *.proto)
KRATOS_VERSION=$(shell go mod graph |grep go-kratos/kratos/v2 |head -n 1 |awk -F '@' '{print $$2}')
KRATOS=$(GOPATH)/pkg/mod/github.com/go-kratos/kratos/v2@$(KRATOS_VERSION)

.PHONY: init
# init env
init:
	go get -u github.com/go-kratos/kratos/cmd/kratos/v2
	go get -u google.golang.org/protobuf/cmd/protoc-gen-go
	go get -u google.golang.org/grpc/cmd/protoc-gen-go-grpc
	go get -u github.com/go-kratos/kratos/cmd/protoc-gen-go-http/v2
	go get -u github.com/go-kratos/kratos/cmd/protoc-gen-go-errors/v2
	go get -u github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2
	go get -u github.com/google/wire/cmd/wire
	go get -u github.com/envoyproxy/protoc-gen-validate

.PHONY: grpc
# generate grpc code
grpc:
	protoc --proto_path=. \
		--proto_path=./third_party \
		--go_out=paths=source_relative:. \
		--go-grpc_out=paths=source_relative:. \
		$(API_PROTO_FILES)

.PHONY: http
# generate http code
http:
	protoc --proto_path=. \
		--proto_path=./third_party \
		--go_out=paths=source_relative:. \
		--go-http_out=paths=source_relative:. \
		$(API_PROTO_FILES)

.PHONY: errors
# generate errors code
errors:
	protoc --proto_path=. \
           --proto_path=./third_party \
           --go_out=paths=source_relative:. \
           --go-errors_out=paths=source_relative:. \
           $(API_PROTO_FILES)

.PHONY: validate
# generate validate code
validate:
	protoc --proto_path=. \
           --proto_path=./third_party \
           --go_out=paths=source_relative:. \
           --validate_out=paths=source_relative,lang=go:. \
           $(API_PROTO_FILES)

.PHONY: proto
# generate internal proto
proto:
	protoc --proto_path=. \
		--proto_path=./third_party \
 		--go_out=paths=source_relative:. \
		$(INTERNAL_PROTO_FILES)

.PHONY: api
# generate api proto
api:
	protoc --proto_path=. \
		--proto_path=./third_party \
 		--go_out=paths=source_relative:. \
		$(API_PROTO_FILES)

.PHONY: swagger
# generate swagger file
swagger:
	protoc --proto_path=. \
		--proto_path=./third_party \
		--openapiv2_out . \
		--openapiv2_opt logtostderr=true \
		--openapiv2_opt json_names_for_fields=false \
		$(API_PROTO_FILES)

.PHONY: generate
# generate client code
generate:
	go generate ./...

.PHONY: build
# build
build:
	mkdir -p bin/ && go build -ldflags "-X main.Version=$(VERSION)" -o ./bin/ ./...

.PHONY: test
# test
test:
	go test -v -cover ./...

.PHONY: all
# generate all
all:
	make generate;
	make grpc;
	make http;
	make errors;
	make validate;
	make proto;
	make api;
	make swagger;
	make build;
	make test;


# show help
help:
	@echo ''
	@echo 'Usage:'
	@echo ' make [target]'
	@echo ''
	@echo 'Targets:'
	@awk '/^[a-zA-Z\-\_0-9]+:/ { \
	helpMessage = match(lastLine, /^# (. *) /); \
		if (helpMessage) { \
			helpCommand = substr($$1, 0, index($$1, ":") - 1); \ helpMessage = substr(lastLine, RSTART + 2, RLENGTH); \ printf"\033[36m%-22s\033[0m %s\n", helpCommand,helpMessage; \
		} \
	} \
	{ lastLine = $$0 }' $(MAKEFILE_LIST)

.DEFAULT_GOAL := help
Copy the code

Installation steps

Install the Kratos command-line tool

# Use go get
go get -u github.com/go-kratos/kratos/cmd/kratos/v2@latest
If you want to install go 1.16, you need to add the latest version or specify the latest version
go install github.com/go-kratos/kratos/cmd/kratos/v2
Copy the code

Installing Other Tools

Other tools can be easily installed by using the upgrade command of the Kratos command-line tool

kratos upgrade
Copy the code

You can also install other tools manually

go get -u github.com/go-kratos/kratos/cmd/kratos/v2 go get -u github.com/go-kratos/kratos/cmd/protoc-gen-go-http/v2 go get -u github.com/go-kratos/kratos/cmd/protoc-gen-go-errors/v2 go get -u google.golang.org/protobuf/cmd/protoc-gen-go go  get -u google.golang.org/grpc/cmd/protoc-gen-go-grpc go get -u github.com/envoyproxy/protoc-gen-validateGo 1.16 requires the latest or specified version to be installedgo install github.com/go-kratos/kratos/cmd/kratos/v2 go install github.com/go-kratos/kratos/cmd/protoc-gen-go-http/v2 go  install github.com/go-kratos/kratos/cmd/protoc-gen-go-errors/v2 go install google.golang.org/protobuf/cmd/protoc-gen-go  go install google.golang.org/grpc/cmd/protoc-gen-go-grpc go install github.com/envoyproxy/protoc-gen-validateCopy the code

The actual use

Specify a custom template repository when creating a project

kratos new hello -r https://github.com/xxx/xxx.git
Copy the code

Specify a tag or branch for the template repository when creating the project

kratos new hello -b test
Copy the code

Build proto

Proto can be built using the Kratos command-line tool or using makefiles

Kratos command-line tool

# kratos proto client XXXX # kratos proto client XXXX # kratos proto client XXXX
kratos client proto .
Copy the code

Makefile

make api
Copy the code

Generate HTTP through proto

Defining an HTTP interface

    / / want to use the proto generating code HTTP file need to import "Google/API/annotations. Proto";
  rpc SayHello (HelloRequest) returns (HelloReply)  {
    option (google.api.http) = {
        // Define a GET interface and map name to HelloRequest
        get: "/helloworld/{name}".// Additional interfaces can be added
        additional_bindings {
            // Define a POST interface and map the body to HelloRequest
            post: "/v1/greeter/say_hello",
            body: "*",}}; }Copy the code

The generated code

kratos proto client xxx.proto --go-http_opt=omitempty=false
# or
make http
Copy the code

Generate the Errors code via proto

Define error code

enum ErrorReason {
  // Set the default error code
  option (errors.default_code) = 500;
  
  // Set a separate error code for an enumeration
  USER_NOT_FOUND = 0 [(errors.code) = 404];

  CONTENT_MISSING = 1 [(errors.code) = 400];;
}
Copy the code

The generated code

The Errors code is only generated if the proto file declares an error code

kratos proto client xxx.proto
# or
make errors
Copy the code

Validate code is generated by proto

Define the validate

message Request {
    int64 id = 1 [(validate.rules).int64 = {gt: 0}];
    int32 age = 2 [(validate.rules).int32 = {gt:0, lt: 120}];
    uint32 code = 3 [(validate.rules).uint32 = {in: [1.2.3]}];
    float score = 4 [(validate.rules).float = {not_in: [0.99.99]}];
    bool state = 5 [(validate.rules).bool.const = true];
    string path = 6 [(validate.rules).string.const = "/hello"];
    string phone = 7 [(validate.rules).string.len = 11];
    string explain = 8 [(validate.rules).string.min_len = 3];
    string name = 9 [(validate.rules).string = {min_len: 1, max_len: 10}];
    string card = 10 [(validate.rules).string.pattern = "(? i)^[0-9a-f]+$"];
    Info info = 11 [(validate.rules).message.required = true];
}
Copy the code

The generated code

The validate code is generated only when a parameter validation rule is declared in the proto file

kratos proto client xxx.proto
# or
make validate
Copy the code

Generate GRPC code through proto

Define the GRPC method

service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply)  {
        option (google.api.http) = {
            get: "/helloworld/{name}"}; }}Copy the code

The generated code

The validate code is generated only when a parameter validation rule is declared in the proto file

kratos proto client xxx.proto
# or
make validate
Copy the code

Generate service code through Proto

The generated code

kratos proto server xxx.proto -t internal/service
Copy the code

reference

  • Go – kratos. Dev/docs/gettin…
  • Go – kratos. Dev/docs/compon…
  • Go – kratos. Dev/docs/compon…
  • Go – kratos. Dev/docs/compon…