gone是可以高效开发Web服务的Golang依赖注入框架
github地址:https://github.com/gone-io/gone
文档地址:https://goner.fun/zh/
使用gRPC通信
首先创建一个grpc目录,在这个目录中初始化一个golang mod:
mkdir grpc
cd grpc
go mod init grpc
编写proto文件,生成golang代码
- 编写协议文件
定义一个简单的Hello服务,包含一个Say方法
文件名:proto/hello.proto
syntax = "proto3";
option go_package="/proto";
package Business;
service Hello {
rpc Say (SayRequest) returns (SayResponse);
}
message SayResponse {
string Message = 1;
}
message SayRequest {
string Name = 1;
}
- 生成golang代码
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
protoc --go_out=. --go_opt=paths=source_relative \
--go-grpc_out=. --go-grpc_opt=paths=source_relative \
proto/hello.proto
其中,protoc的安装参考Protocol Buffer 编译器安装
编写服务端代码
文件名:server/main.go
package main
import (
"context"
"github.com/gone-io/gone"
"github.com/gone-io/gone/goner"
"github.com/gone-io/gone/goner/cmux"
"google.golang.org/grpc"
"grpc/proto"
"log"
)
type server struct {
gone.Flag
proto.UnimplementedHelloServer // 嵌入UnimplementedHelloServer
}
// 重载协议中定义的服务
func (s *server) Say(ctx context.Context, in *proto.SayRequest