【grpc】配置

发布时间 2023-11-21 11:09:52作者: Nones

@


写在前面

  • 相关博文
  • 个人博客首页
  • 免责声明:仅供学习交流使用!开源框架可能存在的风险和相关后果将完全由用户自行承担,本人不承担任何法律责任。

grpc 环境搭建

go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
git clone -b v1.57.0 --depth 1 https://github.com/grpc/grpc-go

proto

// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// 版本
syntax = "proto3";
// golang 代码生成路径
option go_package = "./gorpc;";

// 包名称
package gorpc;

// 注册的服务名称
// rpc 是对应的方法 
// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloResponse) {}
}

// 请求结构体
// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// 返回结构体
// The response message containing the greetings
message HelloResponse {
  string message = 1;
}


证书

1. 生成 rsa key

openssl genrsa -des3 -out server.key 2048

2. 生成 ca crt

openssl req -new -x509 -key server.key -out ca.crt -days 3650

3. 生成 csr

openssl req -new -key server.key -out server.csr

4. openssl.cnf (/usr/lib/ssl/openssl.cnf) 【WINDOWS 默认为 openssl.cfg

1)复制一份你安装的openssl的bin目录里面的openssl.cnf 
2)找到 [ CA_default ],打开 copy_extensions = copy (就是把前面的#去掉)
3)找到[ req ],打开 req_extensions = v3_req # The extensions to add to a certificate request
4)找到[ v3_req ],添加 subjectAltName = @alt_names
5)添加新的标签 [ alt_names ],和标签字段
DNS.1 = *.org.haha.com
DNS.2 = *.haha.com

5. 生成证书私钥 test.key

openssl genpkey -algorithm RSA -out test.key

6. 通过私钥test.key生成证书请求文件test.csr(注意cfg和cnf)

openssl req -new -nodes -key test.key -out test.csr -days 3650 -subj "/C=cn/OU=myorg/O=mycomp/CN=myname" -config ./openssl.cnf -extensions v3_req
test.csr是上面生成的证书请求文件。
ca.crt/server.key 是CA证书文件和key,用来对test.csr进行签名认证。这两个文件在第一部分生成。

7.生成SAN证书

openssl x509 -req -days 365 -in test.csr -out test.pem -CA ca.crt -CAkey server.key -CAcreateserial -extfile ./openssl.cnf -extensions v3_req

然后就可以用在 GO 1.15 以上版本的GRPC通信了

服务器加载代码

creds, err := credentials.NewServerTLSFromFile("test.pem", "test.key")

客户端加载代码

creds,err := credentials.NewClientTLSFromFile("test.pem","*.org.haha.com")

参考资料


交个朋友

  • github learnselfs