Table of Contents
- Introduction
- Prerequisites
- Installing Revel
- Creating a New Revel Project
- Understanding Revel’s Structure
- Creating Routes
- Adding Controllers and Actions
- Creating Views
- Working with Templates
- Handling Forms
- Adding a Database
- Conclusion
Introduction
In this tutorial, we will learn how to create a Go web application using the Revel framework. Revel is a high productivity, full-stack web framework for the Go programming language. By the end of this tutorial, you will be able to create a basic web application with routing, controllers, views, templates, and even database integration.
Prerequisites
Before starting this tutorial, you should have a basic understanding of the Go programming language and web development concepts. You should have Go installed on your machine and be familiar with command-line operations.
Installing Revel
To begin, we need to install the Revel framework. Open your terminal and execute the following command:
go get github.com/revel/cmd/revel
Creating a New Revel Project
Once the installation is complete, we can create a new Revel project. In your terminal, navigate to the directory where you want to create your project and run the following command:
revel new mywebapp
This will create a new directory named “mywebapp” with the basic structure of a Revel application.
Understanding Revel’s Structure
Before diving into building our web application, let’s take a moment to understand the structure of a Revel project. Inside the “mywebapp” directory, you will find the following main directories:
app
- Contains the application code, including controllers, views, and other supporting files.conf
- Contains the application configuration files.public
- Contains public resources like CSS, JavaScript, and images.tests
- Contains test cases for the application.
Creating Routes
Routes determine how URLs are mapped to controllers and actions in your application. Open the conf/routes
file and you will see a default route specified:
# Home page
GET / App.Index
This route maps the root URL (“/”) to the Index
action in the App
controller. You can add more routes to handle different URLs and actions.
Adding Controllers and Actions
Controllers handle incoming requests and define actions to be executed. Create a new file called app/controllers/app.go
and add the following code:
package controllers
import "github.com/revel/revel"
type App struct {
*revel.Controller
}
func (c App) Index() revel.Result {
return c.Render()
}
Here, we define the App
controller with an Index
action. The Index
action simply renders the corresponding view for the home page.
Creating Views
Views in Revel are responsible for generating HTML content. Create a new file called app/views/App/Index.html
and add the following code:
{{set . "title" "Welcome to My Web App"}}
<h1>Welcome to My Web App</h1>
This is a simple view that displays a welcome message.
Working with Templates
Revel uses Go’s built-in templating engine to generate dynamic content. Let’s enhance our view to include some dynamic data. Update the App/Index.html
file as follows:
{{set . "title" "Welcome to My Web App"}}
<h1>Welcome, {{.UserName}}</h1>
In the controller’s Index
action, we can pass data to the view using the RenderArgs
field:
func (c App) Index() revel.Result {
c.RenderArgs["UserName"] = "John Doe"
return c.Render()
}
Now, when the user visits the home page, they will see a personalized message.
Handling Forms
Revel provides convenient ways to handle form submissions. Let’s create a simple form and handle its submission. Update the App/Index.html
file as follows:
{{set . "title" "Welcome to My Web App"}}
<h1>Welcome, {{.UserName}}</h1>
<form action="/submit" method="post">
<input type="text" name="message" placeholder="Enter your message">
<button type="submit">Submit</button>
</form>
In the App
controller, add a new action called Submit
to handle form submission:
func (c App) Submit() revel.Result {
message := c.Params.Form.Get("message")
// Process the message...
return c.Redirect(App.Index)
}
This action retrieves the form data and performs any necessary processing.
Adding a Database
Revel integrates well with various databases. Let’s add support for a popular database, PostgreSQL, to our application.
-
Install the Go PostgreSQL driver:
```shell go get github.com/lib/pq ```
-
Update the
conf/app.conf
file to specify the database connection details:```config db.import = github.com/lib/pq db.driver = postgres db.spec = user=your_username password=your_password dbname=mywebapp sslmode=disable ```
-
Create a new file called
app/models/message.go
and add the following code:```go package models import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" ) type Message struct { gorm.Model Content string } ``` This defines a simple model for storing messages.
-
In the
App
controller’sSubmit
action, update the code to save the submitted message to the database:```go func (c App) Submit() revel.Result { message := c.Params.Form.Get("message") db, err := gorm.Open("postgres", revel.Config.StringDefault("db.spec", "")) if err != nil { panic(err) } defer db.Close() db.AutoMigrate(&models.Message{}) db.Create(&models.Message{Content: message}) return c.Redirect(App.Index) } ``` This code creates a new record in the `messages` table with the submitted message.
Conclusion
Congratulations! You have successfully created a Go web application using the Revel framework. You have learned how to set up a Revel project, create routes, define controllers and actions, work with views and templates, handle form submissions, and even integrate a PostgreSQL database. This tutorial only scratches the surface of what Revel can do, but it provides a solid foundation for building more complex web applications. Continue exploring the Revel documentation to discover more features and best practices.
Remember to practice and experiment with the code provided to strengthen your understanding. Happy coding!