简介
小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系。
系列
业务流程
初始化项目
开发环境
为少
的本地开发环境
go version
# go version go1.14.14 darwin/amd64
protoc --version
# libprotoc 3.15.7
protoc-gen-go --version
# protoc-gen-go v1.26.0
protoc-gen-go-grpc --version
# protoc-gen-go-grpc 1.1.0
protoc-gen-grpc-gateway --version
初始代码结构
使用 go mod init server
初始化 Go
项目,这里(demo
)我直接采用 server
作为当前 module
名字。
go-grpc-gateway-v2-microservice
├── auth // 鉴权微服务
│ ├── api
│ ├── ├── gen
│ ├── ├── ├── v1 // 生成的代码将放到这里,v1 表示第一个 API 版本
│ │ ├── auth.proto
│ │ └── auth.yaml
│ ├── auth
│ │ └── auth.go // service 的具体实现
│ ├── wechat
│ └── main.go // 鉴权 gRPC server
├── gateway // gRPC-Gateway,反向代理到各个 gRPC Server
│ └── main.go
├── gen.sh // 根据 `auth.proto` 生成代码的命令
└── go.mod
领域(auth.proto)定义
syntax = "proto3";
package auth.v1;
option go_package="server/auth/api/gen/v1;authpb";
// 客户端发送一个 code
message LoginRequest {
string code = 1;
}
// 开发者服务器返回一个自定义登录态(token)
message LoginResponse {
string access_token = 1;
int32 expires_in = 2; // 按 oauth2 约定走
}
service AuthService {
rpc Login (LoginRequest) returns (LoginResponse);
}
使用 gRPC-Gateway 暴露 RESTful JSON API
auth.yaml
定义
type: google.api.Service
config_version: 3
http:
rules:
- selector: auth.v1.AuthService.Login
post: /v1/auth/login
body: "*"
根据配置生成代码
使用 gen.sh
生成 gRPC-Gateway
相关代码
PROTO_PATH=./auth/api
GO_OUT_PATH=./auth/api/gen/v1
protoc -I=$PROTO_PATH --go_out=paths=source_relative:$GO_OUT_PATH auth.proto
protoc -I=$PROTO_PATH --go-grpc_out=paths=source_relative:$GO_OUT_PATH auth.proto
protoc -I=$PROTO_PATH --grpc-gateway_out=paths=source_relative,grpc_api_configuration=$PROTO_PATH/auth.yaml:$GO_OUT_PATH auth.proto
运行:
sh gen.sh
成功后,会生成 auth.pb.go
,auth_grpc.pb.go
,auth.pb.gw.go
文件,代码结构如下:
├── auth
│ ├── api
│ ├── ├── gen
│ ├── ├── ├── v1
│ ├── ├── ├── ├── auth.pb.go // 生成的 golang 相关的 protobuf 代码
│ ├── ├── ├── ├── auth_grpc.pb.go // 生成 golang 相关的 gRPC Server 代码
│ ├── ├── ├── ├── auth.pb.gw.go // 生成 golang 相关的 gRPC-Gateway 代码
│ │ ├── auth.proto
│ │ └── auth.yaml
│ ├── auth
│ │ └── auth.go
│ ├── wechat
│ └── main.go
├── gateway
│ └── main.go
├── gen.sh
└── go.mod
整理一下包:
go mod tidy
初步实现 Auth gRPC Service Server
实现 AuthServiceServer
接口
我们查看生成 auth_grpc.pb.go
代码,找到 AuthServiceServer
定义:
……
// AuthServiceServer is the server API for AuthService service.
// All implementations must embed UnimplementedAuthServiceServer
// fo