I've ran into a problem as follows:
When I make a curl
request to my beego
app
curl http://localhost:8080/controller/path -X POST -H 'Content-Type: multipart/form-data; charset=UTF-8' -F “file=@file.csv;filename=file.csv” -F “name=first”
I want to access name
param from my controller, but when I try
func (c *Controller) Path() {
...
var name string
c.Ctx.Input.Bind(&name, "name")
// or I've tried 'name := c.GetString("name")'
...
}
result is always an empty string as name
variable.
What am I doing wrong ? How can I access params in this case ? Please any advice welcome !
Update 1
I've tried Parse to struct
approach, with no luck...
type DataParams struct {
Name string `form:"name"`
}
cLDP := DataParams{}
if err := c.ParseForm(&cLDP); err != nil {
return ret, err
}
Update 2
as of comment, I've tried
c.Ctx.Input.ParseFormOrMulitForm(99999)
var name string
c.Ctx.Input.Bind(&name, "name")
Update 3
after trying altogether I'm lost...
name := c.Ctx.Input.Query("name")
params := c.Ctx.Input.Params()
name2 := c.GetString("name")
c.Ctx.Input.ParseFormOrMulitForm(99999)
params2 := c.Ctx.Input.Params()
fmt.Println("Debug 2->", name)
fmt.Println("Debug 5->", name2)
fmt.Println("Debug 3->", params)
fmt.Println("Debug 4->", params2)
output is
Debug 2->
Debug 3-> map[...]
Debug 4-> map[...]
Debug 5->
no name param detected
Update 4
if I use c.Ctx.Input.RequestBody
it not surprisingly is empty
And still no luck :(
You should be able to access the name
parameter value using the Query method, like so:
name := c.Ctx.Input.Query("name")
If you want to use Bind
you can do something like this:
names := []string{}
if err := c.Ctx.Input.Bind(&names, "name"); err != nil {
panic(err)
}
log.Println(name[0]) // first
But you'll also have to update your curl
to specifically declare the name
parameter as an array with index:
curl ... -F "name[0]=first"
This is because internally Go stores a form's parameter values in a slice of strings (see url.Values) and beego is using this as well, so after beego parses the form it will look like this url.Values{"name": []string{"first"}}
and so beego does not know how to bind []string{"first"}
into a plain string
.
change the "Content-Type: multipart/form-data to enctype:multipart/form-data