Creating Our First Beego Project
Create a new Beego application using the bee command line.
We'll cover the following
Create a new project
There is a traditional way to create a new Beego project. We can create a new Go module, add all the required packages, and create source files and directories ourselves.
We can create a new project named hello_beego
using the following command:
bee new hello_beego
Execute the project
In the project directory, execute the following command to run the project:
bee run
The default port on which the server runs is 8080. The API /
, which is the root (endpoint) or the homepage of the application, is implemented by default in the projects created using the Bee command line.
Playground
Here is the source code of a project created using the bee new
command. The bee run
command is added to the start script. When we click the “Run” button, it runs the Beego server and renders the API /
.
appname = hello_beego httpport = 8080 runmode = dev
The /
route is defined in the routers/router.go
file:
Line 1: Specifies that this file belongs to the
routers
package. Packages are used to organize and structure code in Go.Lines 3–6: These lines import two other packages:
hello_beego/controllers
andgithub.com/beego/beego/v2/server/web
. Thecontrollers
package contains the controller that will handle the routes, and theweb
package is from the Beego framework itself.Lines 8–10: This is an initialization function in Go, which is automatically executed when the package is imported or the application starts.
Line 9: The route
/
is mapped toMainController
.
The handler function is defined in the file controllers/default.go
:
Lines 7–9: Controller structure is defined.
Lines 11–15: The function
Get()
is the handler of HTTP GET API/
. The context of the controller isc
.Lines 12–13:
Website
andEmail
keys are set in the context data.Line 14: The view template is defined in the context of the controller. After the controller execution, this template is rendered.
The file views/index.tpl
is the template that renders the HTML view:
Lines 3–95: The code encaptures the HTML view. The lines include the header and body of the HTML view as well.
Lines 86 and 88: The variables set in the handler function
Website
andEmail
are used in the template.
Upon successful execution of the code, the terminal will show the output similar to the following:
The Beego welcome page will be displayed on the output: