2016-04-23 43 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