Accessing HTTP POST parameters in Go

边缘青年_739d · · 489 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

I ran into a little issue as I tried to POST to a Go backend using Axios but I could not get the parameters I was sending.

I was doing this:

func handleReq(w http.ResponseWriter, req *http.Request) {
    err := req.ParseForm()
    if err != nil {
        panic(err)
    }
    v := req.Form
    owner := req.Form.Get("owner")
    name := req.Form.Get("name")
    //...
}

but the two parameters I was looking for were not available. Why?

Turns out that I was assuming Axios sent the parameters using Content-Type:application/x-www-form-urlencoded but by default it’s using Content-Type:application/json.

Note: you can configure it to use application/x-www-form-urlencoded, check https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

This means that to access the parameters I need to decode them using json.Decoder.

Here is some sample code that does the trick:

type myData struct {
    Owner string
    Name  string
}

func handleAddNewRepo(w http.ResponseWriter, req *http.Request) {
    decoder := json.NewDecoder(req.Body)

    var data myData
    err := decoder.Decode(&data)
    if err != nil {
        panic(err)
    }

    owner := data.Owner
    name := data.Name
    //...
}

https://flaviocopes.com/golang-http-post-parameters/


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:边缘青年_739d

查看原文:Accessing HTTP POST parameters in Go

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

489 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传