相关疑难解决方法(0)

如何使Go HTTP客户端不自动跟踪重定向?

我目前正在Go中编写一些与REST API交互的软件.我正在尝试查询的REST API端点返回HTTP 302重定向以及指向资源URI的HTTP Location标头.

我正在尝试使用Go脚本来获取HTTP Location标头以供以后处理.

以下是我目前正在实现的功能:

package main

import (
        "errors"
        "fmt"
        "io/ioutil"
        "net/http"
)

var BASE_URL = "https://api.stormpath.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"

func noRedirect(req *http.Request, via []*http.Request) error {
        return errors.New("Don't redirect!")
}

func main() {

        client := &http.Client{
            CheckRedirect: noRedirect
        }
        req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
        req.SetBasicAuth(STORMPATH_API_KEY_ID, STORMPATH_API_KEY_SECRET)

        resp, err := client.Do(req)

        // If we get here, it means one of two things: either this http request
        // actually failed, or …
Run Code Online (Sandbox Code Playgroud)

rest redirect http go

47
推荐指数
4
解决办法
3万
查看次数

标签 统计

go ×1

http ×1

redirect ×1

rest ×1