You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用golang.org/x/oauth2 mock TokenURL时出现missing access_token错误

解决oauth2: server response missing access_token错误

你的问题出在mock服务器没有设置正确的Content-Type响应头。golang.org/x/oauth2包在解析Token响应时,要求返回的Content-Type必须是application/json(或兼容的媒体类型),否则会无法正确解析响应体,进而判定缺少access_token字段。

修改你的mock服务器代码,在返回JSON前添加Content-Type头:

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == "/token" {
        // 必须添加这个头,否则oauth2包无法正确解析响应
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(struct {
            AccessToken  string    `json:"access_token"`
            TokenType    string    `json:"token_type"`
            RefreshToken string    `json:"refresh_token"`
            Expiry       time.Time `json:"expiry"`
        }{
            AccessToken:  "access-token",
            TokenType:    "Bearer",
            RefreshToken: "refresh-token",
            Expiry:       time.Now().Add(2 * time.Hour),
        })
    }
}))
defer server.Close()
mockConfig.Endpoint.TokenURL = server.URL + "/token"

真实的OAuth2服务商在返回Token响应时,都会正确设置Content-Type: application/json头,所以你的代码在生产环境能正常运行,但测试时mock服务器遗漏了这个关键头,导致解析失败。

内容的提问来源于stack exchange,提问作者SebastianWi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:42:13