英文:
Cannot parse posted form data from beego
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是Go语言的新手,正在使用beego框架。
我试图从以下表单中获取提交的表单数据:
<form action="/hello" method="post">
{{.xsrfdata}}
标题:<input name="title" type="text" /><br>
内容:<input name="body" type="text" /><br>
<input type="submit" value="提交" />
</form>
然后将数据传递给控制器:
type HelloController struct {
beego.Controller
}
type Note struct {
Id int `form:"-"`
Title string `form:"title"`
Body string `form:"body"`
}
func (this *HelloController) Get() {
this.Data["xsrfdata"] = template.HTML(this.XSRFFormHTML())
this.TplName = "hello.tpl"
}
func (this *HelloController) Post() {
n := &Note{}
if err := this.ParseForm(&n); err != nil {
s := err.Error()
log.Printf("type: %T; value: %q\n", s, s)
}
log.Printf("Your note title is %s", n.Title)
log.Printf("Your note body is %s", n.Body)
this.Ctx.Redirect(302, "/")
}
但是,我得到的不是输入字段中的字符串值,而是:
Your note title is %!s(*string=0xc82027a368)
Your note body is %!s(*string=0xc82027a378)
我按照文档上的请求处理进行操作,但是不明白为什么无法获取提交的字符串。
英文:
I'm new to go and experiencing beego.
I'm trying to get the posted form data from:
<form action="/hello" method="post">
{{.xsrfdata}}
Title:<input name="title" type="text" /><br>
Body:<input name="body" type="text" /><br>
<input type="submit" value="submit" />
</form>
To the controller:
type HelloController struct {
beego.Controller
}
type Note struct {
Id int `form:"-"`
Title string `form:"title"`
Body string `form:"body"`
}
func (this *HelloController) Get() {
this.Data["xsrfdata"]= template.HTML(this.XSRFFormHTML())
this.TplName = "hello.tpl"
}
func (this *HelloController) Post() {
n := &Note{}
if err := this.ParseForm(&n); err != nil {
s := err.Error()
log.Printf("type: %T; value: %q\n", s, s)
}
log.Printf("Your note title is %s" , &n.Title)
log.Printf("Your note body is %s" , &n.Body)
this.Ctx.Redirect(302, "/")
}
But instead of the string values entered into field I get :
Your note title is %!s(*string=0xc82027a368)
Your note body is %!s(*string=0xc82027a378)
I followed the docs on request processing, but left clueless why can not the posted strings.
答案1
得分: 2
从文档中可以看出,定义接收器结构体应该使用结构体类型,而不是指向该结构体的指针:
func (this *MainController) Post() {
u := User{}
if err := this.ParseForm(&u); err != nil {
//处理错误
}
}
然后,在你的控制器中,如果你这样做会更好...
func (this *HelloController) Post() {
n := Note{}
...
}
关于Go中指针的更多信息,请参考:https://tour.golang.org/moretypes/1
英文:
From the documentation, the way to define the receiver struct should be using a struct type, not a pointer to that struct:
func (this *MainController) Post() {
u := User{}
if err := this.ParseForm(&u); err != nil {
//handle error
}
}
Then, in your controller, the things should be better if you..
func (this *HelloController) Post() {
n := Note{}
...
}
More info about pointers in go: https://tour.golang.org/moretypes/1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论