How to build a Web App with Go and SQLite

Building a Web App with Go and SQLite

If you need to build lean, performant, and scalable applications, Go and SQLite is an excellent choice. In this article, we'll build a small, screaming fast web API using Go and SQLite.

Author: Jeremy Morgan


Part one of a five part series on building a web application with Go. Get the Project source code here

If you need to build lean, performant, and scalable applications, Go and SQLite together are an excellent choice. Web APIs are no exception to that. In a previous post, we learned how you can use Go and SQLite together, and we built a nice little console application. Today, we’re going to build a Web API version of it.

Go is one of the hottest languages in development right now, known for its simple structure and blazing performance.

SQLite has been trending among developers for its ability to host small data very quickly, safely, and contained in a single file.

In this article, you will learn:

  • How to build a Web API with the Gin Web Framework
  • How to create, read, update, and delete records (CRUD) with SQLite and Go
  • How to connect your API to a SQLite Database

Here are the steps we’ll take:

By the time you’re done with this tutorial, you can build screaming fast web applications in Go.

How to build a web app with SQLite and Go

What is Gin?

Gin is a screaming fast, simple web framework. From the website:

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance – up to 40 times faster. If you need smashing performance, get yourself some Gin.

It’s incredibly powerful yet simple to use. You can build Web APIs or complete web applications with it. Today you’ll be able to develop your first Gin application.

What is SQLite?

SQLite is a small, fast, self contained, high reliability SQL database engine. What’s great about SQLite is you don’t need a database server. It’s all self contained in a file that ships with your application. That makes this application small, efficient and portable.

Why SQLite?

  • Great Performance
  • Tiny footprint
  • Self contained (file-based)

You’re likely already using SQLite every day, and you don’t know it. It’s ubiquitous in mobile phones and devices, and SQLite powers many websites today.

What do I need to Build This?

To build this application, you need a computer with

  • Go installed on it
  • A text editor, like Visual Studio Code
  • The database from our Previous Go Project, which you can download here

Optionally I am using DB Browser for SQLite, which is available in Windows, OSX, and Linux. I’m also using Postman to test requests.

I am using Pop!_OS Linux for this demo, but the instructions will be the same if you’re using Linux, OSX, or Windows.

Let’s get started!

Step 1: Create the application

Create a folder on your hard drive and type in the following:

go mod init example.com/personweb

You can name this however you’d like.

Next, we’ll install the libraries we’re going to use for this application:

go get -u github.com/mattn/go-sqlite3
go get -u github.com/gin-gonic/gin

Then, create a new file named main.go and add the following:

package main

import (
	"github.com/gin-gonic/gin"
)

func main() {

}

and save it.

Step 2: Creating a Router

For now, we’re going to set up our router, but the application isn’t going to do anything useful yet.

A router takes incoming requests and routes them to functionality to handle them. If it sees a GET request, it will pass the user off to code used to handle GET requests. If it’s a POST, it will route the user somewhere different. While this sounds complex, Gin handles it very elegantly. Let’s add the following code in our main() function:

r := gin.Default()

// API v1
v1 := r.Group("/api/v1")
{
  v1.GET("person", getPersons)
  v1.GET("person/:id", getPersonById)
  v1.POST("person", addPerson)
  v1.PUT("person/:id", updatePerson)
  v1.DELETE("person/:id", deletePerson)
  v1.OPTIONS("person", options)
}

// By default it serves on :8080 unless a
// PORT environment variable was defined.
r.Run()

Before we go further, let’s look at what this code does.

First, we start up the router:

r := gin.Default()

This fires up a Gin default router we can work with. Now, there are several ways to set up a router in Go, but this pattern is my favorite:

v1 := r.Group("/api/v1")
{

Here we are creating a “Group” for our routes. You can create routes individually, but this way uses less code and is easier to understand. We’re building a group of routes under /api/v1. This means any URI that comes after www.yourdomain.com/api/v1 will be handled in this group. This is version 1 of our API.

Then we handle each request based on the verb sent and the URI.

How to build a web app with SQLite and Go

As you can see above, when a GET request is sent to /api/v1/person, this statement will catch the request and send it to getPersons.

As you go down the list, you can see other verbs being handled.

How to build a web app with SQLite and Go

You may notice with this particular statement, we have :id in the URI. This is a parameter for capturing the ID as it’s passed in, and we’ll learn how to handle that a bit later. But make a note that we specify this parameter in the URL to grab it later.

How to build a web app with SQLite and Go

So we look for a verb, look for the URI, and pass it to the function we want, based on the request.

Step 3: Handler Functions

So now we know we have a set of functions that will handle these requests. For now, let’s drop in those functions and have them return a message so we can verify all of our routes.

First, you’ll need to import net/http so you can send an http response:

import (
	"net/http"
	"github.com/gin-gonic/gin"
)

Now let’s add in the following functions:

func getPersons(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"message": "getPersons Called"})
}

func getPersonById(c *gin.Context) {
	id := c.Param("id")
	c.JSON(http.StatusOK, gin.H{"message": "getPersonById " + id +" Called"})
}

func addPerson(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"message": "addPerson Called"})
}

func updatePerson(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"message": "updatePerson Called"})
}

func deletePerson(c *gin.Context) {
	id := c.Param("id")
	c.JSON(http.StatusOK, gin.H{"message": "deletePerson " + id + " Called"})
}

func options(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"message": "options Called"})
}

If you look at these functions they’re simple to understand. In getPersons:

func getPersons(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"message": "getPersons Called"})
}

We’re defining the function as getPersons and taking in our Gin context as c. This context can give us valuable information, and we change the state of Gin from it.

  • We update the value of c.JSON which tells Gin to return a value in JSON.
  • We specify that we want it to return a 200 OK response, by passing in http.StatusOK.
  • Then we create a message response with the function name included.

In some of those functions, we are also displaying an id. Remember that ID parameter in the URI that we discussed earlier? Here’s how you grab that:

id := c.Param("id")

You can grab any parameter from the URI from the Gin context and use it accordingly.

So let’s see what it looks like.

Step 4: Spot Check with Postman

The first thing we want to do is run the application. At a prompt, run

go build
./personweb

(If you’re in Windows run personweb.exe)

You will now see something like this in your console:

How to build a web app with SQLite and Go

Now your application is listening on port 8080.

Load up Postman and send a GET request to it:

How to build a web app with SQLite and Go

And you’ll notice in the response we have 200 OK and the message we specified earlier.

How to build a web app with SQLite and Go

You can use Postman to run through each route and verify them.

Here we can verify that the ID passed into the URI is being read:

How to build a web app with SQLite and Go

Great! Now that we know the routes are working let’s connect to some data!

Conclusion

In this part of the tutoarial, we created a nice Web API with some routes. You can now see how easy it is to set up a basic web application with Gin.

Now move on to part two of the series where we’ll connect to the database.


Series: Building a Web App with Go and SQLite:


How much do you know about Go? Find out your Go SkillIQ here! Take a free skill assessment.



Related tags:

programming   golang   sqlite   tutorials   gin  
About the author

Jeremy Morgan is a tech blogger, speaker and author. He has been a developer for nearly two decades and has worked with a variety of companies from the Fortune 100 to shoestring startups.

Jeremy loves to teach and learn, writing here on and on his Tech Blog as well as building Pluralsight Courses.

10-day free trial

Sign Up Now