In this tutorial, you will learn how to build traditional web applications and microservices in Go using theGinframework. Gin is a framework which reduces boilerplate code that would normally go into building these applications. It also lends itself very well to creating reusable and extensible pieces of code.
This part of the tutorial will help you set up your project and build a simple application using Gin that will display a list of articles and the article details page.
By the end of this tutorial, you will:
For this tutorial, you will need Go andcurl
installed on your machine.
Note:If you don't havecurl
, you can use any other tool that you would normally use to test API end points.
Gin is a high-performance micro-framework that can be used to build web applications and microservices. It makes it simple to build a request handling pipeline from modular, reusable pieces. It does this by allowing you to write middleware that can be plugged into one or more request handlers or groups of request handlers.
One of the best features of Go is its built-innet/http
library that allows you to create an HTTP server effortlessly. However, it is also less flexible and requires some boilerplate code to implement.
There is no built-in support in Go to handle routes based on a regular expression or a "pattern". You can write code to add this functionality. However, as the number of your applications grows, it is quite likely that you will either repeat such code everywhere or create a library for reuse.
This is the crux of what Gin offers. It contains a set of commonly used functionalities, e.g. routing, middleware support, rendering, that reduce boilerplate code and make writing web applications simpler.
Let's take a quick look at how a request is processed in Gin. The control flow for a typical web application, API server or a microservice looks as follows:
Request -> Route Parser -> [Optional Middleware] -> Route Handler -> [Optional Middleware] -> Response
When a request comes in, Gin first parses the route. If a matching route definition is found, Gin invokes the route handler and zero or more middleware in an order defined by the route definition. We will see how this is done when we take a look at the code in a later section.
The application we'll build is a simple article manager. This application should:
In addition to this functionality, the list of articles and a single article should be accessible in the HTML, JSON and XML formats.
This will allow us to illustrate how Gin can be used to design traditional web applications, API servers and microservices.
To achieve this, we will make use of the following functionalities offered by Gin:
We'll also write tests to validate that all the features work as intended.
Routing is one of the core features that all modern frameworks provide. Any web page or an API end point is accessed by a URL. Frameworks use routes to handle requests to these URLs. If a URL ishttp://www.example.com/some/random/route
, the route will be/some/random/route
.
Gin offers a fast router that's easy to configure and use. Apart from handling specified URLs, Gin routers can also handle patterns and grouped URLs.
In our application, we will:
/
(HTTP GET request),/u
route,/u/login
(HTTP GET request),/u/login
(HTTP POST request),/u/logout
(HTTP GET request),/u/register
(HTTP GET request),/u/register
(HTTP POST request) ,/article
route,/article/create
(HTTP GET request),/article/create
(HTTP POST request), and/article/view/:article_id
(HTTP GET request). Take note of the
:article_id
part in this route. The
:
at the beginning indicates that this is a dynamic route. This means that
:article_id
can contain any value and Gin will make this value available in the route handler.A web application can render a response in various formats like HTML, text, JSON, XML or other formats. API endpoints and microservices typically respond with data, commonly in JSON format but also in any other desired format.
In the next section, we'll see how we can render different types of responses without duplicating any functionality. We will primarily respond to a request with an HTML template. However, we will also define two end points which can respond with JSON or XML data.
In the context of a Go web application, middleware is a piece of code that can be executed at any stage while handling an HTTP request. It is typically used to encapsulate common functionality that you want to apply to multiple routes. We can use middleware before and/or after an HTTP request is handled. Some common uses of middleware include authorization, validation, etc.
If middleware is used before a request is handled, any changes it makes to the request will be available in the main route handler. This is handy if we want to implement some validations on certain requests. On the other hand, if middleware is used after the route handler, it will have the response from the route handler. This can be used to modify the response from the route handler.
Gin allows us to write middleware that implements some common functionality that needs to be shared while handling multiple routes. This keeps the codebase small, separates concerns and improves code maintainability.
We want to ensure that some pages and actions, eg. creating an article, logging out, are available only to users who are logged in. We also want to ensure that some pages and actions, eg. registering, logging in, are available only to users who aren't logged in.
If we were to put this logic in every route, it would be quite tedious, repetitive and error-prone. Luckily, we can create middleware for each of these tasks and reuse them in specific routes.
We will also create middleware that will be applied to all routes. This middleware (setUserStatus
) will check whether a request is from an authenticated user or not. It will then set a flag that can be used in templates to modify the visibility of some of the menu links based on this flag.
This application will only use one external dependency - theGin
framework. We can install the latest version using the following command:
go get -u github.com/gin-gonic/gin
Our application will display a web page using its template. However, there will be several parts such as the header, menu, sidebar, and footer, which will be common across all pages. Go allows us to create reusable template snippets that can be imported in other templates.
The header and the footer will be the common pieces that will be reused across all templates. We will also create the menu in its own template file which will be used by the header template. Finally, we'll create the template for the index page which will import the header and the footer. All the template files will be placed in thetemplates
directory within the project directory.
Let's start by creating the template for the menu intemplates/menu.html
as follows:
<!--menu.html-->
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">
Home
</a>
</div>
</div>
</nav>
Initially, the menu contains only the link to the home page. We will add to this as we add more functionality to the application. The template for the header will be placed in thetemplates/header.html
file as follows:
<!--header.html-->
<!doctype html>
<html>
<head>
<!--Use the `title` variable to set the title of the page-->
<title>{{ .title }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<!--Use bootstrap to make the application look nice-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script async src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body class="container">
<!--Embed the menu.html template at this location-->
{{ template "menu.html" . }}
As you can see, we are using the open source Bootstrap framework. Most of this file is standard HTML. However, take note of two lines. The line containing<title>{{ .title }}</title>
is used to dynamically set the title of the page using the.title
variable that must be set inside the application. Secondly, the line containing{{ template "menu.html" . }}
is used to import the menu template from themenu.html
file. This is how Go lets you import one template in another.
The template for the footer contains static HTML. The template for the index page makes use of the header and the footer and displays a simple
Hello Gin
message:
<!--index.html-->
<!--Embed the header.html template at this location-->
{{ template "header.html" .}}
<h1>Hello Gin!</h1>
<!--Embed the footer.html template at this location-->
{{ template "footer.html" .}}
Like the index template, templates for other pages will reuse the templates for the header and the footer in a similar manner.
Once you have created the templates, it's time to create the entry file for your application. We'll create the
main.go
file for this with the simplest possible web application that will use the index template. We can do this using Gin in four steps:
1. Create the router
The default way to create a router in Gin is as follows:
router := gin.Default()
This creates a router which can be used to define the build of the application.
2. Load the templates
Once you have created the router, you can load all the templates like this:
router.LoadHTMLGlob("templates/*")
This loads all the template files located in thetemplates
folder. Once loaded, these don't have to be read again on every request making Gin web applications very fast.
3. Define the route handler
At the heart of Gin is how you divide the application into various routes and define handlers for each route. We will create a route for the index page and an inline route handler.
router.GET("/", func(c *gin.Context) {
// Call the HTML method of the Context to render a template
c.HTML(
// Set the HTTP status to 200 (OK)
http.StatusOK,
// Use the index.html template
"index.html",
// Pass the data that the page uses (in this case, 'title')
gin.H{
"title": "Home Page",
},
)
})
Therouter.GET
method is used to define a route handler for a GET request. It takes in as parameters the route (/
) and one or more route handlers which are just functions.
The route handler has a pointer to the context (gin.Context
) as its parameter. This context contains all the information about the request that the handler might need to process it. For example, it includes information about the headers, cookies, etc.
The Context also has methods to render a response in HTML, text, JSON and XML formats. In this case, we use thecontext.HTML
method to render an HTML template (index.html
). The call to this method includes additional data in which the value oftitle
is set toHome Page
. This is a value that the HTML template can make use of. In this case, we use this value in the<title>
tag in the header's template.
4. Start the application
To start the application, you can use theRun
method of the router:
router.Run()
This starts the application onlocalhost
and serves on the8080
port by default.
The completemain.go
file looks as follows:
// main.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
var router *gin.Engine
func main() {
// Set the router as the default one provided by Gin
router = gin.Default()
// Process the templates at the start so that they don't have to be loaded
// from the disk again. This makes serving HTML pages very fast.
router.LoadHTMLGlob("templates/*")
// Define the route for the index page and display the index.html template
// To start with, we'll use an inline route handler. Later on, we'll create
// standalone functions that will be used as route handlers.
router.GET("/", func(c *gin.Context) {
// Call the HTML method of the Context to render a template
c.HTML(
// Set the HTTP status to 200 (OK)
http.StatusOK,
// Use the index.html template
"index.html",
// Pass the data that the page uses (in this case, 'title')
gin.H{
"title": "Home Page",
},
)
})
// Start serving the application
router.Run()
}
To execute the application from the command line, go to your application directory and execute the following command:
go build -o app
This will build your application and create an executable namedapp
which you can run as follows:
./app
If all goes well, you should be able to access your application athttp://localhost:8080
and it should look like this:
The directory structure of your application at this stage should be as follows:
├── main.go
└── templates
├── footer.html
├── header.html
├── index.html
└── menu.html
In this section, we'll add the functionality to display the list of all articles on the index page.
In the previous section, we created the route and the route definition in themain.go
file itself. As the application grows, it would make sense to move the routes definitions in its own file. We'll create a functioninitializeRoutes()
in theroutes.go
file and call this function from themain()
function to set up all the routes. Instead of defining the route handler inline, we'll define them as separate functions.
After making these changes, theroutes.go
file will contain the following:
// routes.go
package main
func initializeRoutes() {
// Handle the index route
router.GET("/", showIndexPage)
}
Since we'll be displaying the list of articles on the index page, we don't need to define any additional routes after we've refactored the code.
Themain.go
file should contain the following code:
// main.go
package main
import "github.com/gin-gonic/gin"
var router *gin.Engine
func main() {
// Set the router as the default one provided by Gin
router = gin.Default()
// Process the templates at the start so that they don't have to be loaded
// from the disk again. This makes serving HTML pages very fast.
router.LoadHTMLGlob("templates/*")
// Initialize the routes
initializeRoutes()
// Start serving the application
router.Run()
}
We will keep the article structure simple with just three fields -Id
,Title
andContent
. This can be represented with astruct
as follows:
type article struct {
ID int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
}
Most applications will use a database to persist the data. To keep things simple, we will keep the list of articles in memory and will initialize the list with two hard-coded articles as follows:
var articleList = []article{
article{ID: 1, Title: "Article 1", Content: "Article 1 body"},
article{ID: 2, Title: "Article 2", Content: "Article 2 body"},
}
We will place the above code in a new file namedmodels.article.go
. At this stage, we need a function that will return the list of all articles. We will name this functiongetAllArticles()
and place it in the same file. We will also write a test for it. This test will be namedTestGetAllArticles
and will be placed in themodels.article_test.go
file.
Let's start by creating the unit test (TestGetAllArticles
) for thegetAllArticles()
function. After creating this unit test, themodels.article_test.go
file should contain the following code:
// models.article_test.go
package main
import "testing"
// Test the function that fetches all articles
func TestGetAllArticles(t *testing.T) {
alist := getAllArticles()
// Check that the length of the list of articles returned is the
// same as the length of the global variable holding the list
if len(alist) != len(articleList) {
t.Fail()
}
// Check that each member is identical
for i, v := range alist {
if v.Content != articleList[i].Content ||
v.ID != articleList[i].ID ||
v.Title != articleList[i].Title {
t.Fail()
break
}
}
}
This unit test uses thegetAllArticles()
function to fetch the list of all articles. This test first makes sure that the article list fetched by this function and the article list present in the global variablearticleList
are identical. It then loops over the article list to verify that each article is identical. The test fails if either of these two checks fail.
Once we have written the test, we can proceed to write the actual code. Themodels.article.go
file should contain the following code:
// models.article.go
package main
type article struct {
ID int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
}
// For this demo, we're storing the article list in memory
// In a real application, this list will most likely be fetched
// from a database or from static files
var articleList = []article{
article{ID: 1, Title: "Article 1", Content: "Article 1 body"},
article{ID: 2, Title: "Article 2", Content: "Article 2 body"},
}
// Return a list of all the articles
func getAllArticles() []article {
return articleList
}
Since the list of articles will be displayed on the index page, we don't need to create a new template. However, we do need to change theindex.html
template to replace the current content with the list of articles.
To make this change, we'll assume that the list of articles will be passed to the template in a variable namedpayload
. With this assumption, the following snippet should show the list of all articles:
{{range .payload }}
<!--Create the link for the article based on its ID-->
<a href="/article/view/{{.ID}}">
<!--Display the title of the article -->
<h2>{{.Title}}</h2>
</a>
<!--Display the content of the article-->
<p>{{.Content}}</p>
{{end}}
This snippet will loop over all items in thepayload
variable and display the title and the content of each article. The above snippet will also link to each article. However, since we have not yet defined route handlers for displaying individual articles, these links won't work as expected.
The updatedindex.html
file should contain the following code:
<!--index.html-->
<!--Embed the header.html template at this location-->
{{ template "header.html" .}}
<!--Loop over the `payload` variable, which is the list of articles-->
{{range .payload }}
<!--Create the link for the article based on its ID-->
<a href="/article/view/{{.ID}}">
<!--Display the title of the article -->
<h2>{{.Title}}</h2>
</a>
<!--Display the content of the article-->
<p>{{.Content}}</p>
{{end}}
<!--Embed the footer.html template at this location-->
{{ template "footer.html" .}}
Before we create the handler for the index route, we will create a test to define the expected behavior of this route handler. This test will check for the following conditions:
Home Page
.The code for the test will be placed in theTestShowIndexPageUnauthenticated
function in thehandlers.article_test.go
file. We will place helper functions used by this function in thecommon_test.go
file.
The content ofhandlers.article_test.go
is as follows:
// handlers.article_test.go
package main
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// Test that a GET request to the home page returns the home page with
// the HTTP code 200 for an unauthenticated user
func TestShowIndexPageUnauthenticated(t *testing.T) {
r := getRouter(true)
r.GET("/", showIndexPage)
// Create a request to send to the above route
req, _ := http.NewRequest("GET", "/", nil)
testHTTPResponse(t, r, req, func(w *httptest.ResponseRecorder) bool {
// Test that the http status code is 200
statusOK := w.Code == http.StatusOK
// Test that the page title is "Home Page"
// You can carry out a lot more detailed tests using libraries that can
// parse and process HTML pages
p, err := ioutil.ReadAll(w.Body)
pageOK := err == nil && strings.Index(string(p), "<title>Home Page</title>") > 0
return statusOK && pageOK
})
}
The content ofcommon_test.go
is as follows:
package main
import (
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/gin-gonic/gin"
)
var tmpArticleList []article
// This function is used for setup before executing the test functions
func TestMain(m *testing.M) {
//Set Gin to Test Mode
gin.SetMode(gin.TestMode)
// Run the other tests
os.Exit(m.Run())
}
// Helper function to create a router during testing
func getRouter(withTemplates bool) *gin.Engine {
r := gin.Default()
if withTemplates {
r.LoadHTMLGlob("templates/*")
}
return r
}
// Helper function to process a request and test its response
func testHTTPResponse(t *testing.T, r *gin.Engine, req *http.Request, f func(w *httptest.ResponseRecorder) bool) {
// Create a response recorder
w := httptest.NewRecorder()
// Create the service and process the above request.
r.ServeHTTP(w, req)
if !f(w) {
t.Fail()
}
}
// This function is used to store the main lists into the temporary one
// for testing
func saveLists() {
tmpArticleList = articleList
}
// This function is used to restore the main lists from the temporary one
func restoreLists() {
articleList = tmpArticleList
}
To implement this test, we have written some helper functions. These will also help us reduce boilerplate code when we write additional tests to test similar functionality.
TheTestMain
function sets Gin to use the test mode and calls the rest of the test functions. ThegetRouter
function creates and returns a router in a manner similar to the main application. ThesaveLists()
function saves the original article list in a temporary variable. This temporary variable is used by therestoreLists()
function to restore the article list to its initial state after a unit test is executed.
Finally, thetestHTTPResponse
function executes the function passed in to see if it returns a boolean true value — indicating a successful test, or not. This function helps us avoid duplicating the code needed to test the response of an HTTP request.
To check the HTTP code and the returned HTML, we'll do the following:
Create a new router,
testHTTPResponse()
with this new function to complete the test.We will create all route handlers for article related functionality in thehandlers.article.go
file. The handler for the index page,showIndexPage
performs the following tasks:
1. Fetches the list of articles
This can be done using thegetAllArticles
function defined previously:
articles := getAllArticles()
2. Renders theindex.html
template passing it the article list
This can be done using the code below:
c.HTML(
// Set the HTTP status to 200 (OK)
http.StatusOK,
// Use the index.html template
"index.html",
// Pass the data that the page uses
gin.H{
"title": "Home Page",
"payload": articles,
},
)
The only difference from the version in the previous section is that we're passing the list of articles which will be accessed in the template by the variable namedpayload
.
Thehandlers.article.go
file should contain the following code:
// handlers.article.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func showIndexPage(c *gin.Context) {
articles := getAllArticles()
// Call the HTML method of the Context to render a template
c.HTML(
// Set the HTTP status to 200 (OK)
http.StatusOK,
// Use the index.html template
"index.html",
// Pass the data that the page uses
gin.H{
"title": "Home Page",
"payload": articles,
},
)
}
If you now build and run your application and visithttp://localhost:8080
in a browser, it should look like this:
These are the new files added in this section:
├── common_test.go
├── handlers.article.go
├── handlers.article_test.go
├── models.article.go
├── models.article_test.go
└── routes.go
In the last section, while we displayed a list of articles, the links to the articles didn't work. In this section, we'll add handlers and templates to display an article when it is selected.
We can set up a new route to handle requests for a single article in the same manner as in the previous route. However, we need to account for the fact that while the handler for all articles would be the same, the URL for each article would be different. Gin allows us to handle such conditions by defining route parameters as follows:
router.GET("/article/view/:article_id", getArticle)
This route will match all requests matching the above path and will store the value of the last part of the route in the route parameter namedarticle_id
which we can access in the route handler. For this route, we will define the handler in a function namedgetArticle
.
The updated
routes.go
file should contain the following code:
// routes.go
package main
func initializeRoutes() {
// Handle the index route
router.GET("/", showIndexPage)
// Handle GET requests at /article/view/some_article_id
router.GET("/article/view/:article_id", getArticle)
}
We need to create a new template at
templates/article.html
to display the content of a single article. This can be created in a manner similar to the
index.html
template. However, instead of the
payload
variable containing the list of articles, in this case it will contain a single article.
The test for the handler of this route will check for the following conditions:
The code for the test will be placed in theTestArticleUnauthenticated
function in thehandlers.article_test.go
file. We will place helper functions used by this function in thecommon_test.go
file.
The handler for the article page,getArticle
performs the following tasks:
1. Extracts the ID of the article to display
To fetch and display the right article, we first need to extract its ID from the context. This can be extracted as follows:
2. Fetches the article
This can be done using thegetArticleByID()
function defined in themodels.article.go
file:
article, err := getArticleByID(articleID)
ThegetArticleByID
function (inmodels.article.go
) is as follows:
func getArticleByID(id int) (*article, error) {
for _, a := range articleList {
if a.ID == id {
return &a, nil
}
}
return nil, errors.New("Article not found")
}
This function loops through the article list and returns the article whose ID matches the ID passed in. If no matching article is found it returns an error indicating the same.
3. Renders thearticle.html
template passing it the article
This can be done using the code below:
c.HTML(
// Set the HTTP status to 200 (OK)
http.StatusOK,
// Use the article.html template
"article.html",
// Pass the data that the page uses
gin.H{
"title": article.Title,
"payload": article,
},
)
The updatedhandlers.article.go
file should contain the following code:
// handlers.article.go
package main
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
func showIndexPage(c *gin.Context) {
articles := getAllArticles()
// Call the HTML method of the Context to render a template
c.HTML(
// Set the HTTP status to 200 (OK)
http.StatusOK,
// Use the index.html template
"index.html",
// Pass the data that the page uses
gin.H{
"title": "Home Page",
"payload": articles,
},
)
}
func getArticle(c *gin.Context) {
// Check if the article ID is valid
if articleID, err := strconv.Atoi(c.Param("article_id")); err == nil {
// Check if the article exists
if article, err := getArticleByID(articleID); err == nil {
// Call the HTML method of the Context to render a template
c.HTML(
// Set the HTTP status to 200 (OK)
http.StatusOK,
// Use the index.html template
"article.html",
// Pass the data that the page uses
gin.H{
"title": article.Title,
"payload": article,
},
)
} else {
// If the article is not found, abort with an error
c.AbortWithError(http.StatusNotFound, err)
}
} else {
// If an invalid article ID is specified in the URL, abort with an error
c.AbortWithStatus(http.StatusNotFound)
}
}
If you now build and run your application and visithttp://localhost:8080/article/view/1
in a browser, it should look like this:
The new files added in this section are as follows:
└── templates
└── article.html
In this section, we will refactor the application a bit so that, depending on the request headers, our application can respond in HTML, JSON or XML format.
So far, we've been using theHTML
method of Gin's context to render directly from route handlers. This is fine when we always want to render HTML. However, if we want to change the format of the response based on the request, we should refactor this part out into a single function that takes care of rendering. By doing this, we can let the route handler focus on validation and data fetching.
A route handler has to do the same kind of validation, data fetching and data processing irrespective of the desired response format. Once this part is done, this data can be used to generate the response in the desired format. If we need an HTML response, we can pass this data to the HTML template and generate the page. If wee need a JSON response, we can convert this data to JSON and send it back. Likewise for XML.
We'll create arender
function inmain.go
that will be used by all the route handlers. This function will take care of rendering in the right format based on the request'sAccept
header.
In Gin, theContext
passed to a route handler contains a field namedRequest
This field contains theHeader
field which contains all the request headers. We can use theGet
method onHeader
to extract theAccept
header as follows:
// c is the Gin Context
c.Request.Header.Get("Accept")
If this is set to
application/json
, the function will render JSON,application/xml
, the function will render XML, andThe completerender
function is as follows:
// Render one of HTML, JSON or CSV based on the 'Accept' header of the request
// If the header doesn't specify this, HTML is rendered, provided that
// the template name is present
func render(c *gin.Context, data gin.H, templateName string) {
switch c.Request.Header.Get("Accept") {
case "application/json":
// Respond with JSON
c.JSON(http.StatusOK, data["payload"])
case "application/xml":
// Respond with XML
c.XML(http.StatusOK, data["payload"])
default:
// Respond with HTML
c.HTML(http.StatusOK, templateName, data)
}
}
Since we are now expecting JSON and XML responses if the respective headers are set, we should add tests to thehandlers.article_test.go
file to test these conditions. We will add tests to:
Accept
header is set toapplication/json
Accept
header is set toapplication/xml
These will be added as functions namedTestArticleListJSON
andTestArticleXML
.
The route handlers don't really need to change much as the logic for rendering in any format is pretty much the same. All that needs to be done is use therender
function instead of rendering using thec.HTML
methods.
For example, theshowIndexPage
route handler will change from
func showIndexPage(c *gin.Context) {
articles := getAllArticles()
// Call the HTML method of the Context to render a template
c.HTML(
// Set the HTTP status to 200 (OK)
http.StatusOK,
// Use the index.html template
"index.html",
// Pass the data that the page uses
gin.H{
"title": "Home Page",
"payload": articles,
},
)
}
to
func showIndexPage(c *gin.Context) {
articles := getAllArticles()
// Call the render function with the name of the template to render
render(c, gin.H{
"title": "Home Page",
"payload": articles}, "index.html")
}
Retrieving the List of Articles in JSON Format
To see our latest updates in action, build and run your application. Then execute the following command:
curl -X GET -H "Accept: application/json"http://localhost:8080/
This should return a response as follows:
[{"id":1,"title":"Article 1","content":"Article 1 body"},{"id":2,"title":"Article 2","content":"Article 2 body"}]
As you can see, our request got a response in the JSON format because we set theAccept
header toapplication/json
.
Retrieving an Article in XML Format
Let's now get our application to respond with the details of a particular article in the XML format. To do this, first start your application as mentioned above. Now execute the following command:
curl -X GET -H "Accept: application/xml" http://localhost:8080/article/view/1
This should return a response as follows:
<article><ID>1</ID><Title>Article 1</Title><Content>Article 1 body</Content></article>
As you can see, our request got a response in the XML format because we set theAccept
header toapplication/xml
.
Since we've been using tests to create specifications for our route handlers and models, we should constantly be running them to ensure that the functions work as expected. Let's now run the tests that we have written and see the results. In your project directory, execute the following command:
go test -v
Executing this command should result in something similar to this:
=== RUN TestShowIndexPageUnauthenticated
[GIN] 2016/06/14 - 19:07:26 | 200 | 183.315µs | | GET /
--- PASS: TestShowIndexPageUnauthenticated (0.00s)
=== RUN TestArticleUnauthenticated
[GIN] 2016/06/14 - 19:07:26 | 200 | 143.789µs | | GET /article/view/1
--- PASS: TestArticleUnauthenticated (0.00s)
=== RUN TestArticleListJSON
[GIN] 2016/06/14 - 19:07:26 | 200 | 51.087µs | | GET /
--- PASS: TestArticleListJSON (0.00s)
=== RUN TestArticleXML
[GIN] 2016/06/14 - 19:07:26 | 200 | 38.656µs | | GET /article/view/1
--- PASS: TestArticleXML (0.00s)
=== RUN TestGetAllArticles
--- PASS: TestGetAllArticles (0.00s)
=== RUN TestGetArticleByID
--- PASS: TestGetArticleByID (0.00s)
PASS
ok github.com/demo-apps/go-gin-app 0.084s
As can be seen in this output, this command runs all the tests that we have written and, in this case, indicates that our application is working as we intend it to. If you take a close look at the output, you'll notice that Go made HTTP requests in the course of testing the route handlers.
In this tutorial, we created a new web application using Gin and gradually added more functionality. We used tests to build robust route handlers and saw how we can reuse the same code to render a response in multiple formats with minimal effort.