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akyJ1ZSyrRwSZZmNXzd0S4XY3oV19DOiyrLl3qBxhgw33pLYla5dIAs_KnrGVmLSpNJT61T810kqN-dT1c4EFMZ1iz7Bfh4RucK4oHGZmPlR3znqMMijirK8QT7ukTJvhG-TlmfsBMe0r_9UjdQ9wxjZ7pDi7pfYKVOv55O9Lzk2PbAjIHe3UKiA",
"not-before-policy": 1549293916,
"session_state": "66b3d62d-b3c6-42bb-8679-f0ded0e78957",
"scope": "openid email profile"
}
我正在使用的结构如下:
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
Expiry time.Time `json:"expires_in"`
}
解码响应后,我尝试打印响应:
var authToken Token
json.Unmarshal(response.Body, &authToken)
fmt.Println("-------------------- accessToken " + authToken.AccessToken)
fmt.Println("-------------------- refreshToken " + authToken.RefreshToken)
fmt.Println("-------------------- expires ", authToken.Expiry)
fmt.Println("-------------------- type " + authToken.TokenType)
只有第一个AccessToken具有值,其他所有内容均为空。
我也尝试使用json.NewDecoder(response.Body).Decode(&authToken)
相同的结果。
我的方法有什么问题吗?
答案 0 :(得分:2)
您必须从json.Unmarshal
或decoder.Decode
检查错误。
而"expires_in": 299,
不是时间,是整数。
代码:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
Expiry int `json:"expires_in"`
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var authToken Token
if err := decoder.Decode(&authToken); err != nil {
fmt.Fprintf(w, "error: %s", err)
return
}
fmt.Println("-------------------- accessToken " + authToken.AccessToken)
fmt.Println("-------------------- refreshToken " + authToken.RefreshToken)
fmt.Println("-------------------- expires ", authToken.Expiry)
fmt.Println("-------------------- type " + authToken.TokenType)
})
http.ListenAndServe(":8000", nil)
}
卷曲:
curl -XPOST 'http://localhost:8000' -H 'Content-Type: application/json' -d '{
"access_token": "at",
"refresh_token": "rt",
"expires_in": 299,
"token_type": "bearer"
}'
结果:
-------------------- accessToken at
-------------------- refreshToken rt
-------------------- expires 299
-------------------- type bearer