使用go-swagger的微服务间通信



我的需求是调用第二个API(服务B),作为认证用户对服务a的单个请求的一部分。

我正在通过一个计划好的项目练习go-swagger框架。我试图实现的一点是从微服务a到微服务b的真实调用。我已经实现了没有身份验证,但无法验证这个内部调用。
我在微服务a端遇到EOF错误,服务停止。我还在微服务b端看到runtime error: index out of range [1] with length 1错误。

以下是ms-A(遵循goswagger文档)与ms-B通信的代码:

transport := httptransport.New(apiclient.DefaultHost, apiclient.DefaultBasePath, apiclient.DefaultSchemes)
clientm := apiclient.New(transport, strfmt.Default)
bearerTokenAuth:= httptransport.BearerToken(os.Getenv("Authorization"))
resp, err := clientm.Show.Show(show.NewShowParams(),bearerTokenAuth)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%#vn", resp.Payload.Prompt)
微服务- b中的Show端点是测试这种内部通信的简单入口点。我确实在yaml文件中添加了安全的路径,如下所示:
/show:
get:
description: "To test the entrypoint"
operationId: "show"
tags:
- "show"
security:
- Bearer: [ ]
responses:
200:
description: "Success response on hiting endpoint"
schema:
$ref: "#/definitions/Show"
400:
description: Bad Request
404:
description: items not found
500:
schema:
type: string
description: Server error

错误
Microservice-A错误
//service-A which is used to hit show-endpoint of service-B
go run cmd/ustore-server/main.go --scheme http --port=8080
2021/10/08 01:47:00 Serving ustore at http://127.0.0.1:8080
2021/10/08 01:47:06 Get "http://localhost:9090/v1/show": EOF
exit status 1
Microservice-B错误
go run ./cmd/datastore-server/main.go --port=9090
2021/10/08 01:32:36 Serving datastore at http://127.0.0.1:9090
2021/10/08 01:34:14 http: panic serving 127.0.0.1:46040: runtime error: index out of range [1] with length 1
goroutine 23 [running]:

在查看了参数和上面提到的错误后,我终于解决了问题,现在它工作了。

这里我修改的是service-A中的代码:

//token received for user authentication by service-A
bearerHeader := params.HTTPRequest.Header.Get("Authorization")

//connection with service-B client
transport := httptransport.New(apiclient.DefaultHost,apiclient.DefaultBasePath,apiclient.DefaultSchemes)
clientm := apiclient.New(transport, strfmt.Default)

//spliting the key and token(string) and pass only the token part
bearerTokenAuth:= httptransport.BearerToken(strings.Split(bearerHeader, " ")[1])
//receive response of the service-B endpoint
resp, err := clientm.Show.Show(show.NewShowParams(),bearerTokenAuth)
if err != nil {
log.Fatal(err)
}

fmt.Printf("%#vn", resp.Payload.Prompt)

相关内容

  • 没有找到相关文章

最新更新