在 Go 中将字符串从 HTTP 请求转换为数据结构

Jon*_*son 1 go

我有一个 HTTP Post 方法,它成功地将数据发布到外部第三方 API 并返回响应。

然后,我需要从此响应返回的数据发布到我的数据库。

响应包含一些数据,但我只需要其中的“access_token”和“refresh_token”。

因此,我试图做的是将响应从字符串转换为我创建的新数据结构中的各个组件,然后传递到我的数据库。

然而,尽管数据已成功写入我的浏览器,但数据显示为空白。我显然做了一些根本错误的事情,但不确定是什么......

这是我的代码:

type data struct {
    Access_token  string `json:"access_token"`
    Refresh_token string `json:"refresh_token"`
}

func Fetch(w http.ResponseWriter, r *http.Request) {

    client := &http.Client{}

    q := url.Values{}

    q.Add("grant_type", "authorization_code")
    q.Add("client_id", os.Getenv("ID"))
    q.Add("client_secret", os.Getenv("SECRET"))
    q.Add("redirect_uri", "https://callback-url.com")
    q.Add("query", r.URL.Query().Get("query"))

    req, err := http.NewRequest("POST", "https://auth.truelayer-sandbox.com/connect/token", strings.NewReader(q.Encode()))

    if err != nil {
        log.Print(err)
        fmt.Println("Error was not equal to nil at first stage.")
        os.Exit(1)
    }

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Error sending request to server")
        os.Exit(1)
    }

    respBody, _ := ioutil.ReadAll(resp.Body)

    d := data{}

    err = json.NewDecoder(resp.Body).Decode(&d)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(d.Access_token)
    fmt.Println(d.Refresh_token)

    w.WriteHeader(resp.StatusCode)
    w.Write(respBody)

}
Run Code Online (Sandbox Code Playgroud)

bla*_*een 6

ioutil.ReadAll你阅读正文时,已经。第二次传给NewDecoder(resp.Body)流的时候就被消耗掉了。

您可以使用json.Unmarshal(respBody, &d).

还有一个建议,不要忽略上面的错误ioutil.ReadAll