我目前正在使用 Go 写一些和 REST API 交互软件。我试着查询 REST API 端点返回 HTTP 302 重定向和指向资源 URI 的 HTTP Location 标头。 3 |8 J6 k0 Y6 |" G9 W1 L4 @7 j8 ?我试着用我的 Go 脚本来获取 HTTP Location 标头供以后处理。 ( D; u, W6 c8 v7 {这是我目前为实现这一功能所做的:9 h& I+ _) w2 k. }
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()}5 a6 m9 i! a1 f) Q i