Home Development API Golang Blog – Beego process simple form using GET and POST method

Golang Blog – Beego process simple form using GET and POST method

202
0


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

Step 1:

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


Golang Blog – Beego process simple form using GET and POST method | Full Software Development

– Add below code in body section.


 {{.LayoutContent}}
 

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




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 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/"
)

func init() {
    .Router("/", &controllers.MainController{})
    .Router("/about", &controllers.AboutController{})
	.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



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here