【发布时间】: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 返回的内容。
【问题讨论】: