0

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.

Karlom
  • 13,323
  • 27
  • 72
  • 116
  • You are getting the pointer addresses, what about if you change log.Printf("Your note title is %s" , &n.Title) for this -> log.Printf("Your note title is %s" , n.Title) – chespinoza Apr 23 '16 at 03:21
  • Then I get things like `Your note title is 0xc820267d18` – Karlom Apr 23 '16 at 15:23
  • But, checking the documentation the way to define the struct (in your case Note) is as a struct type not as a pointer (&) to that struct, then in your code you should be n:=Note{} – chespinoza Apr 23 '16 at 15:40
  • 1
    You are right. please answer and I'll accept. Thanks! – Karlom Apr 23 '16 at 15:45

1 Answers1

2

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

chespinoza
  • 2,638
  • 1
  • 23
  • 46