我目前正在使用 Go 写一些和 REST API 交互软件。我试着查询 REST API 端点返回 HTTP 302 重定向和指向资源 URI 的 HTTP Location 标头。 ?& u% w4 ~8 h8 s& z' {2 L我试着用我的 Go 脚本来获取 HTTP Location 标头供以后处理。 ' p' L* T c7 S0 R6 E. ?这是我目前为实现这一功能所做的:4 m+ z; K6 a& g& H7 \7 C; X
package mainimport ( "errors" "fmt" "io/ioutil" "net/http")var BASE_URL = "https://api.example.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(EXAMPLE_API_KEY_ID,EXAMPLE_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 we got an http redirect response,and should process it. if err != nil if resp.StatusCode == 302 fmt.Println("got redirect") else panic("HTTP request failed.") } defer resp.Body.Close()}" G6 H3 Q& i- `3 x, w