【问题标题】:Trying to make a HTTP request and return the result of that request in an app that uses go/gin尝试发出 HTTP 请求并在使用 go/gin 的应用程序中返回该请求的结果
【发布时间】:2021-12-05 03:34:20
【问题描述】:

我昨天刚拿起 Go,我想知道如何使用 Gin 制作的 API 发出 HTTP 请求并返回该请求的结果。

这是返回另一个请求结果的端点的代码

func ProvideAccessToken(c *gin.Context) {
    body := bindings.RequestAccessTokenBody{}

    err := c.ShouldBind(&body)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        log.Println(err)
        return
    }

    if body.Code == "" || body.GrantType == "" || body.RedirectURI == "" {
        c.String(http.StatusBadRequest, "Bad Request")
        return
    }
    res, err := helpers.ExchangeCodeForToken(body.GrantType, body.RedirectURI, body.Code)

    if err != nil {
        c.JSON(res.StatusCode, gin.H{"error": err.Error()})
        return
    }
    defer res.Body.Close()
    c.Header("Content-Type", "application/json")
    c.JSON(200, res.Body)
}

这是发出 HTTP 请求的函数

func ExchangeCodeForToken(grantType string, redirectUri string, code string) (*http.Response, error) {
    authToken := "Basic " + encodeClientSecretAndId()
    body := url.Values{}
    body.Set("grant_type", grantType)
    body.Set("redirect_uri", redirectUri)
    body.Set("code", code)
    encodedBody := body.Encode()
    client := &http.Client{}

    r, _ := http.NewRequest(http.MethodPost, tokenUrl, strings.NewReader(encodedBody))
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Authorization", authToken)
    res, err := client.Do(r)
    return res, err
}

当我使用邮递员发出请求时,响应只是一个空的 json,如 so{}。 当我的 ProvideAccessToken 函数的结尾更改为

    defer res.Body.Close()
    respbody, err := ioutil.ReadAll(res.Body)
    if err != nil {
        c.JSON(res.StatusCode, gin.H{"error": err.Error()})
        return
    }
    c.Header("Content-Type", "application/json")
    c.JSON(200, string(respbody))

这是我的结果"{\"error\":\"invalid_grant\",\"error_description\":\"Authorization code expired\"}",这是正确的,但格式很奇怪。我只想准确地返回其他 API 返回的内容。

【问题讨论】:

    标签: go go-gin


    【解决方案1】:

    程序的第一个版本将响应正文值编码为 JSON。响应为 {},因为响应正文中没有导出字段。这不是你想要的。

    程序的第二个版本将 JSON 响应编码为 JSON。奇怪的格式是原始 JSON 中 " 的转义。

    将数据按原样写入响应。下面是对第二版程序的修改:

    defer res.Body.Close()
    respbody, err := ioutil.ReadAll(res.Body)
    if err != nil {
        c.JSON(res.StatusCode, gin.H{"error": err.Error()})
        return
    }
    c.Data(200, "application/json", respbody) // <-- note this line
    

    您也可以从一个响应复制到另一个响应:

    defer res.Body.Close()
    c.DataFromReader(200, res.ContentLength, "application/json", res.Body, nil)
    

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 2021-01-25
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      相关资源
      最近更新 更多