Search code examples
gobeegogo-html-template

Cannot parse posted form data from beego


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.


Solution

  • 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