登录
首页 >  Golang >  Go问答

重定向POST请求带有正文数据的GoLang操作

来源:stackoverflow

时间:2024-02-24 10:12:25 367浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《重定向POST请求带有正文数据的GoLang操作》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

我想针对 post 请求使用相同的正文进行重定向。

来自 go 来源 (client.go)

func redirectbehavior(reqmethod string, resp *response, ireq *request) (redirectmethod string, shouldredirect, includebody bool) {
    switch resp.statuscode {
    case 301, 302, 303:
        redirectmethod = reqmethod
        shouldredirect = true
        includebody = false

        // rfc 2616 allowed automatic redirection only with get and
        // head requests. rfc 7231 lifts this restriction, but we still
        // restrict other methods to get to maintain compatibility.
        // see issue 18570.

但有时服务器会为 post 请求返回 302 redirect,这意味着我需要将相同的正文发送到另一个位置。

遇到这种情况我该怎么办?

func FollowRedirectForPost() {
    client := &http.Client{}
    
    req, _ := http.NewRequest(http.MethodPost, "example.com/test", strings.NewReader(url.Values{
        "key": {"value"},
        "key1":{"value1"},
    }.Encode()))

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    client.Do(req) // If server returns 302 Redirect so it means I need make the same request with the same body to
    // a different location. Just imagine i replaced "example.com/test" to "example.com/redirect_url"
}

正确答案


来自 RFC7231

服务器应该在响应中生成 location 标头字段 包含不同 uri 的 uri 引用。用户代理可以 使用位置字段值进行自动重定向。服务器的 响应负载通常包含一个简短的超文本注释,其中包含 指向不同 uri 的超链接。

注意:由于历史原因,用户代理可能会更改请求 后续请求的方法从 post 到 get。如果这 行为是不受欢迎的,307(临时重定向)状态代码 可以用它代替。

因此您可以遵循重定向,新的 uri 位于 location 标头中。你不必这样做。您可以将方法更改为 get,但不是必须这样做。因此本质上,您所做的任何事情都符合 rfc。

您可以通过提供 checkredirect 函数来提供自己的重定向策略。如果 redirectposton302 基本上与 client would do 相同,如果 includebodytrue 并且 redirectmethodpost

func followredirectforpost() {
    client := &http.client{
        checkredirect: redirectposton302,
    }
    
    req, _ := http.newrequest(http.methodpost, "example.com/test", strings.newreader(url.values{
        "key": {"value"},
        "key1":{"value1"},
    }.encode()))

    req.header.add("content-type", "application/x-www-form-urlencoded")
    client.do(req) // if server returns 302 redirect so it means i need make the same request with the same body to
    // a different location. just imagine i replaced "example.com/test" to "example.com/redirect_url"
}

func redirectposton302(req *http.request, via []*http.request) error {
    if len(via) >= 10 {
        return errors.new("stopped after 10 redirects")
    }

    lastreq := via[len(via)-1]
    if req.response.statuscode == 302 && lastreq.method == http.methodpost {
        req.method = http.methodpost

        // get the body of the original request, set here, since req.body will be nil if a 302 was returned
        if via[0].getbody != nil {
            var err error
            req.body, err = via[0].getbody()
            if err != nil {
                return err
            }
            req.contentlength = via[0].contentlength
        }
    }

    return nil
}

最佳做法是更改服务器状态代码 - 307(临时重定向)或 308(永久重定向)。

另一种超级黑客方法可能是 - 更改 checkredirect 函数中的请求 https://github.com/golang/go/blob/master/src/net/http/client.go#L78 https://github.com/golang/go/blob/master/src/net/http/client.go#L691

// example hack
 func FollowRedirectForPost(data io.Reader) {
    client := &http.Client{
        CheckRedirect: func(req *Request, via []*Request) error {
            // check status code etc.
            req.Method = http.MethodPost
            req.Body = data
        }
    }
    
    req, _ := http.NewRequest(http.MethodPost, "example.com/test", data)

    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    client.Do(req) // If server returns 302 Redirect so it means I need make the same request with the same body to
    // a different location. Just imagine i replaced "example.com/test" to "example.com/redirect_url"
}

好了,本文到此结束,带大家了解了《重定向POST请求带有正文数据的GoLang操作》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>