我目前正在使用 Go 写一些和 REST API 交互软件。我试着查询 REST API 端点返回 HTTP 302 重定向和指向资源 URI 的 HTTP Location 标头。 ' X2 N/ M9 d" Y7 f- b5 p我试着用我的 Go 脚本来获取 HTTP Location 标头供以后处理。' {9 ]7 J/ b5 V. P' S. ?$ l
这是我目前为实现这一功能所做的:2 q( K& \$ D% q, Y: {3 `4 n
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()} 3 w: v" u5 B* P; i) a0 @0 J8 x; F$ R