gpt4 book ai didi

go - 如何检测是否调用了重定向

转载 作者:IT王子 更新时间:2023-10-29 02:24:04 26 4
gpt4 key购买 nike

我有以下代码

package main

import (
"log"
"net/http"
)

func fooHandler(w http.ResponseWriter, r *http.Request) {
// Here an if condition, if should redirect or not
http.Redirect(w, r, "http://www.google.com", 301)
// Do something....
// Call function if redirect was invoked

}

func main() {
http.HandleFunc("/", fooHandler)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}

如何检测响应对象中是否写入了重定向?

最佳答案

您可以检查响应的状态(针对 3xx redirection status code ),如 http REST driver 中所示:

    req, err = http.NewRequest(verb, url, body)

if err != nil {
return nil, err
}

for k, v := range headers {
req.Header.Add(k, v)
}

resp, err = d.httpClient.Do(req)

if err != nil {
return nil, err
}

log.Printf("Exec responce: %v\n", resp)

statusCode := resp.StatusCode


if statusCode == 307 { // Temporary Redirect

// For instance (put your own code here)

redirectUrl, ok := resp.Header["Location"]
if !ok {
return nil, fmt.Errorf("%s %s", "Failed to redirect:", "header key 'Location' wasn't found")
}
log.Printf("Redirecting: '%s' --> '%s'", url, redirectUrl[0])
url = redirectUrl[0]
continue

}

关于go - 如何检测是否调用了重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28550020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com