2016-04-23 79 views
0

我是新来的,经历蜜蜂。无法解析来自beego的发布表单数据

我试图让从提交的表单数据:

<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> 

到控制器:但

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) 

我按照the docs的要求处理,但是左无知为什么不能贴出str英格斯。

+0

你所得到的指针地址,大约如果你改变log.Printf( “你的笔记标题为%s”,&n.Title)什么为此 - > log.Printf(“你的笔记标题是%s”,n.Title) – chespinoza

+0

然后我得到像'你的笔记标题是0xc820267d18' – Karlom

+0

但是,检查文档的方式来定义结构(在你的情况注意)作为一个结构类型而不是指向该结构的指针(&),那么在你的代码中你应该是n:= Note {} – chespinoza

回答

1

从文档,定义接收器结构的方法应该是使用结构类型,而不是一个指针,它指向的结构:

func (this *MainController) Post() { 
    u := User{} 
    if err := this.ParseForm(&u); err != nil { 
     //handle error 
    } 
} 

然后,在你的控制器,这个事情应该是你更好。 。

func (this *HelloController) Post() { 
    n := Note{} 
    ... 
} 

约在旅途中三分球更多信息:https://tour.golang.org/moretypes/1