Go gRPC进阶-gRPC转换HTTP(十) (3)

还有个问题,我们使用了bearer token进行接口验证的,怎么把bearer token也添加到swagger中呢?
最后我在grpc-gatewayGitHub上的这个Issues找到解决办法。

在swagger中配置bearer token

1.修改simple.proto文件

syntax = "proto3"; package proto; import "github.com/mwitkow/go-proto-validators/validator.proto"; import "go-grpc-example/10-grpc-gateway/proto/google/api/annotations.proto"; import "go-grpc-example/10-grpc-gateway/proto/google/options/annotations.proto"; message InnerMessage { // some_integer can only be in range (1, 100). int32 some_integer = 1 [(validator.field) = {int_gt: 0, int_lt: 100}]; // some_float can only be in range (0;1). double some_float = 2 [(validator.field) = {float_gte: 0, float_lte: 1}]; } message OuterMessage { // important_string must be a lowercase alpha-numeric of 5 to 30 characters (RE2 syntax). string important_string = 1 [(validator.field) = {regex: "^[a-z]{2,5}$"}]; // proto3 doesn't have `required`, the `msg_exist` enforces presence of InnerMessage. InnerMessage inner = 2 [(validator.field) = {msg_exists : true}]; } option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { security_definitions: { security: { key: "bearer" value: { type: TYPE_API_KEY in: IN_HEADER name: "Authorization" description: "Authentication token, prefixed by Bearer: Bearer <token>" } } } security: { security_requirement: { key: "bearer" } } info: { title: "grpc gateway sample"; version: "1.0"; license: { name: "MIT"; }; } schemes: HTTPS }; service Simple{ rpc Route (InnerMessage) returns (OuterMessage){ option (google.api.http) ={ post:"/v1/example/route" body:"*" }; // //禁用bearer token // option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = { // security: { } // Disable security key // }; } }

2.重新编译生成simple.swagger.json

大功告成!

验证测试

1.添加bearer token

Go gRPC进阶-gRPC转换HTTP(十)

2.调用接口,正确返回数据

Go gRPC进阶-gRPC转换HTTP(十)

3.传递不合规则的数据,返回违反数据验证逻辑错误

Go gRPC进阶-gRPC转换HTTP(十)

总结

本篇介绍了如何使用grpc-gateway让gRPC同时支持HTTP,最终转成的Restful Api支持bearer token验证、数据验证。同时生成swagger文档,方便API接口对接。

教程源码地址:https://github.com/Bingjian-Zhu/go-grpc-example

参考文档:
https://eddycjy.com/tags/grpc-gateway/
https://segmentfault.com/a/1190000008106582

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzpjxj.html