登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-02-20 18:12:25 134浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《使用 go-swagger 实现微服务之间的通信》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我的要求是调用第二个 api(服务 b)作为经过身份验证的用户向服务 a 发出的单个请求的一部分。

我正在通过一个计划的项目练习 go-swagger 框架。我试图实现的要点之一是从微服务 a 到微服务 b 的真实调用。我已经在没有身份验证的情况下实现了,但无法验证此内部调用。

我在微服务 a 端遇到 eof 错误并且服务停止。我还看到微服务 b 端出现 runtime 错误:索引超出范围 [1],长度为 1 错误。

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

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("%#v\n", 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

错误

微服务-错误
//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
微服务-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("%#v\n", resp.Payload.Prompt)

以上就是《使用 go-swagger 实现微服务之间的通信》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>