DEV Community

Cover image for Building a Web App With Go, Gin and React
Francis Sunday
Francis Sunday

Posted on

 

Golang Gin Building a Web App With Go, Gin and React

This article was originally posted on My Blog

TL;DR: In this tutorial, I'll show you how easy it is to build a web application with Go and the Gin framework and add authentication to it. Check out the Github repo for the code we're going to write.


Gin is a high-performance micro-framework that delivers a very minimalistic framework that carries with it only the most essential features, libraries, and functionalities needed 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.

Gin Features

Gin is a fast, simple yet fully featured and very efficient web framework for Go. Check out some of the features below that makes it a worthy framework to consider for your next Golang project.

  • Speed: Gin is built for speed. The framework offers a Radix tree based routing, small memory foot print. No reflection. Predictable API performance.
  • Crash-Free: Gin has the capability of catching crashes or panics during runtime, and can recover from it, this way your application will be always available.
  • Routing: Gin provides a routing interface to allow you express how your web application or API routes should look.
  • JSON Validation: Gin can parse and validate the JSON requests easily, checking for the existence of required values.
  • Error Management: Gin provides a convenient way to collect all the errors occurred during a HTTP request. Eventually, a middleware can write them to a log file, to a database and send them through the network.
  • Built-In Rendering: Gin provides an easy to use API for JSON, XML, and HTML rendering.

Prerequisites

To follow along with this tutorial, you'll need to have Go installed on your machine, a web browser to view the app, and a command line to execute build commands.

Go or as its normally called; "Golang", is a programming language developed by Google for building modern software. Go is a language designed to get stuff done efficiently and fast. The key benefits of Go include:

  • Strongly typed and garbage collected
  • Blazing fast compile times
  • Concurrency built in
  • Extensive standard library

Head over to the downloads section of the Go website, to get Go running on your machine.

Building An App With Gin

We'll be building a simple joke listing app with Gin. Our app will simply list some silly dad jokes. We are going to add authentication to it, all logged-in users will have the privilege to like and view jokes.

This will allow us illustrate how Gin can be used to develop web applications, and/or APIs.

golang-gin-demo-shot

We'll be making use of the following functionalities offered by Gin:

  • Middleware
  • Routing
  • Routes Grouping

Ready, Set, Go

We will write our entire Go application in a main.go file. Since its a small application, its going to be easy to build the application with just go run from the terminal.

We'll create a new directory golang-gin in our Go workspace, and then a main.go file in it:

$ mkdir -p $GOPATH/src/github.com/user/golang-gin
$ cd $GOPATH/src/github.com/user/golang-gin
$ touch main.go
Enter fullscreen mode Exit fullscreen mode

The content of the main.go file:

package main

import (
  "net/http"

  "github.com/gin-gonic/contrib/static"
  "github.com/gin-gonic/gin"
)

func main() {
  // Set the router as the default one shipped with Gin
  router := gin.Default()

  // Serve frontend static files
  router.Use(static.Serve("/", static.LocalFile("./views", true)))

  // Setup route group for the API
  api := router.Group("/api")
  {
    api.GET("/", func(c *gin.Context) {
      c.JSON(http.StatusOK, gin.H {
        "message": "pong",
      })
    })
  }

  // Start and run the server
  router.Run(":3000")
}
Enter fullscreen mode Exit fullscreen mode

We'll need to create some more directories for our static files. In the same directory as the main.go file, let's create a views folder. In the views folder, create a js folder and an index.html file in it.

The index.html file will be very simple for now:

<!DOCTYPE html>
<html>
<head>
  <title>Jokeish App</title>
</head>

<body>
  <h1>Welcome to the Jokeish App</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Before we test what we have to far, let's install the added dependencies:

$ go get -u github.com/gin-gonic/gin
$ go get -u github.com/gin-gonic/contrib/static
Enter fullscreen mode Exit fullscreen mode

To see what's working, we'll need to start our server by running go run main.go.

go-gin-gorun-1

Once the application is running, navigate to http://localhost:3000 in your browser. If all went well, you should see level 1 header text Welcome to the Jokeish App displayed.

golang-welcome-de

Defining The API

Let's add some more code in our main.go file, for our API definitions. We'll update our main function with two routes /jokes/ and /jokes/like/:jokeID, to the route group /api/.

func main() {
  // ... leave the code above untouched...

  // Our API will consit of just two routes
  // /jokes - which will retrieve a list of jokes a user can see
  // /jokes/like/:jokeID - which will capture likes sent to a particular joke
  api.GET("/jokes", JokeHandler)
  api.POST("/jokes/like/:jokeID", LikeJoke)
}

// JokeHandler retrieves a list of available jokes
func JokeHandler(c *gin.Context) {
  c.Header("Content-Type", "application/json")
  c.JSON(http.StatusOK, gin.H {
    "message":"Jokes handler not implemented yet",
  })
}

// LikeJoke increments the likes of a particular joke Item
func LikeJoke(c *gin.Context) {
  c.Header("Content-Type", "application/json")
  c.JSON(http.StatusOK, gin.H {
    "message":"LikeJoke handler not implemented yet",
  })
}
Enter fullscreen mode Exit fullscreen mode

The content of the main.go file, should look like this:

package main

import (
  "net/http"

  "github.com/gin-gonic/contrib/static"
  "github.com/gin-gonic/gin"
)

func main() {
  // Set the router as the default one shipped with Gin
  router := gin.Default()

  // Serve frontend static files
  router.Use(static.Serve("/", static.LocalFile("./views", true)))

  // Setup route group for the API
  api := router.Group("/api")
  {
    api.GET("/", func(c *gin.Context)