登录
首页 >  Golang >  Go问答

实现 GET 请求重定向到 POST 请求传递数据的方法

来源:stackoverflow

时间:2024-03-07 20:09:31 331浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《实现 GET 请求重定向到 POST 请求传递数据的方法》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

当用户通过 get 请求点击某个 url 时,我想将他们重定向到另一个位置的 post 请求。

package main


import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "net/url"
)

func old(w http.responsewriter, r *http.request) {
    newurl := "/new"
    var bdy = []byte(`title=buy cheese and bread for breakfast.`)

    r.method = "post"
    r.url, _ = url.parse(newurl)
    r.requesturi = newurl
    r.body = ioutil.nopcloser(bytes.newreader(bdy))
    r.header.set("content-type", "application/x-www-form-urlencoded")
    http.redirect(w, r, newurl, 302)
}

func new(w http.responsewriter, r *http.request) {
    r.parseform()
    fmt.printf("method:%v\n", r.method)
    fmt.printf("title:%v\n", r.form.get("title"))
}

func main() {
    http.handlefunc("/", old)
    http.handlefunc("/new", new)
    port := 8000
    fmt.printf("listening on %v\n", port)
    if err := http.listenandserve(fmt.sprintf(":%v", port), nil); err != nil {
        log.fatal("listenandserve: ", err)
    }
}

当我点击“/”时,我最终被重定向到“/new”,但带有 get 请求且没有表单数据:

method:get
title:

如果我直接卷曲“/new”,我会得到:

curl -XPOST localhost:8000/new -d "title=Buy cheese and bread for breakfast."

Method:POST
Title:Buy cheese and bread for breakfast.

解决方案


不幸的是,我不相信重定向可以更改动词(例如,GETPOST)或向请求添加数据。它只能更改 URL。

请参阅 Redirect () 了解更多信息。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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