douketangyouzh5219 2018-10-30 03:05
浏览 512

如何将包含一些数据的GET请求重定向到POST请求?

When a user hits a certain url with a GET request I'd like to redirect them to a POST request at another location.

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
", r.Method)
    fmt.Printf("Title:%v
", r.Form.Get("title"))
}

func main() {
    http.HandleFunc("/", old)
    http.HandleFunc("/new", new)
    port := 8000
    fmt.Printf("listening on %v
", port)
    if err := http.ListenAndServe(fmt.Sprintf(":%v", port), nil); err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

When I hit "/" I end up getting redirected to "/new" but with a GET request and no form data:

Method:GET
Title:

If I curl "/new" directly I get :

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

Method:POST
Title:Buy cheese and bread for breakfast.
  • 写回答

3条回答 默认 最新

  • dtny30176 2018-10-30 03:22
    关注

    Unfortunately I don't believe a redirect can change the verb (e.g., GET, POST) or add data to the request. It can only change the URL.

    See Redirect () for more information.

    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条