Beego process simple form using GET and POST method

Beego process simple form using GET and POST method

Original post

In below example we are creating a simple Contact Us page. For which we are creating a form in template, new controller, set the route for controller, call Get method to load the page and send the form data using Post moethod.

Step 1:

to the views folder [srcdemoProjectviews] and create basic layout which we can use in all CMS pages.
– Create homelayout.html write below code in head section.

{{.Title}}

– Add below code in body section.

 {{.LayoutContent}}
 

View layout
– Now Create another file contactusTemplate.html with below code.

Name:
Email:

When user will click on submit button page will redirect to same page “/contactus” but method is Post. Hence, it will display another page.
– Now create another file thankyouTemplate.html with below code.

{{if .name}} Thank you, {{.name}}, we update you on {{.email}}. {{end}}

{{.name}} and {{.email}} variables will display values submitted by user.

Step 2:

Go to the controllers folder [srcdemoProjectcontrollers]
– Now create ContactusController this we can use to display a Contact Us page.
– Write below code in contactus.go

package controllers

type ContactusController struct {
	Common
}

func (this *ContactusController) Get() {
	this.TplName = "contactusTemplate.html"
}

func (this *ContactusController) Post() {
	this.TplName = "thankyouTemplate.html"
	this.Data["name"] = this.GetString("name")
	this.Data["email"] = this.GetString("email")
}

In about ContactusController we have Get() method which is loads the contactusTemplate.html. The Post method will loads process the form data and pass to thankyouTemplate.html.

Step 3:

Go to the routers folder [srcdemoProjectrouters] and open the router.go file. Add below line in router.go to call the ContactusController’s Get and Post Method.
– The updated code in router.go is as follow:

package routers

import (
	"demoProject/controllers"
	"github.com/astaxie/beego"
)

func init() {
    beego.Router("/", &controllers.MainController{})
    beego.Router("/about", &controllers.AboutController{})
	beego.Router("/contactus", &controllers.ContactusController{})
}

Step 4:

Now using commond prompt go to the [srcdemoProject] folder and run the commond “bee run watchall”
– In browser now hit the URL http://127.0.0.1:8080/contactus
Run BeeRun Bee