我正在嘗試從接受有效負載的 POST 端點檢索回應。
curl
請求:
curl --request POST \
--url https://api.io/v1/oauth/token \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{
"userToken": "[email protected]:MyUserProfileToken"
}'
我可以這樣做:
func GetJWT() string {
endpoint := "https://api.io/v1/oauth/token"
payload := strings.NewReader(`{
"userToken":"[email protected]:MyUserProfileToken"
}`)
req, _ := http.NewRequest("POST", endpoint, payload)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
return string(body)
}
和
payload := strings.NewReader("{\n \"userToken\": \"[email protected]:MyUserProfileToken\"\n}")
但是,當我嘗試為電子郵件和令牌傳遞字串指標并宣告有效負載時
func GetJWT(userEmail, userToken *string) string {
endpoint := "https://api.io/v1/oauth/token"
payload := strings.NewReader("{\n \"userToken\": \*userEmail\":\"\*userToken\n}")
req, _ := http.NewRequest("POST", endpoint, payload)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
return string(body)
}
未知轉義回傳錯誤(有效載荷宣告的第 53 列)。
如何轉義字串指標,以便可以連接userEmail
、“:”和userToken
uj5u.com熱心網友回復:
我在這里看到了幾個問題。
首先:我認為“未知轉義”錯誤訊息是由于\*
不是\*
合法的轉義字符引起的。
第二:Golang 不支持字串插值。所以userEmail
anduserToken
變數實際上從未在你的GetJWT
函式中使用過。
Sprintf
您可以使用標準庫fmt
包中的變數將變數格式化為字串。看起來像這樣:
fmt.Sprintf("{\n \"userToken\" : \"%s:%s\" \n}", *userEmail, *userToken)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/507701.html