User Creation And Authentication in Golang Part 1

Elijah Omolo
3 min readMar 30, 2022

PART 1 Connecting to a database using Golang

The ability to create and authenticate users is one of the most basic functions of any application. User creation requires a comprehensive understanding of database CRUD operations as well as authentication which is the mechanism by which a user is identified and resources provided based on that identity. This article should hopefully provide a path towards the mastery of the concepts required to achieve this.

This series of articles will walk you through creating an application with user login and authentication which then displays content on a template depending on the user identity. It’s split into 3 parts to b

In part 1 of this article, we will cover creating a database and user table then ensuring that we can connect to and query it using Go.

Prerequisites:

  • An installation of Go. For installation instructions, see Installing Go.
  • A tool to edit your code. Any text editor you have will work fine, I use Goland.
  • A command terminal. Go works well using any terminal on Linux and Mac, and on PowerShell or cmd in Windows.
  • A local installation of PostgreSQL
  • Installation of the PSQL CLI

Create a folder for your code:

  1. In your command terminal, under the desired path, create a directory for your code called ‘myapp’.
$ mkdir myapp
$ cd myapp

2. Create a module in which you can manage dependencies you will add during this tutorial. Run the go mod init command, giving it your new code’s module path.

$ go mod init myapp
go: creating new go.mod: module myapp

This command creates a go.mod file in which dependencies you add will be listed for tracking. For more, be sure to see Managing dependencies.

Create a database:

In this step, you’ll be creating the ‘myapp’ database:

  1. Open the PSQL shell
$ psql
postgress=# CREATE DATABASE myapp;
CREATE DATABASE

2. Use the command \l to list databases:

Name    | Owner  | Encoding | Collate | Ctype | Access privileges-----------+--------+----------+---------+-------+-------------------myapp     | eomolo | UTF8     | C       | C     |postgres  | eomolo | UTF8     | C       | C     |template0 | eomolo | UTF8     | C       | C     | =c/postgress        +|        |          |         |       | eomolo=CTc/postgresstemplate1 | eomolo | UTF8     | C       | C     | =c/postgress        +|        |          |         |       | eomolo=CTc/eomolotestdb    | eomolo | UTF8     | C       | C     |(5 rows)

Create the Users Table:

Execute the following SQL query to create the Users table, this will be used to demonstrate all future operations:

DROP TABLE IF EXISTS users;CREATE TABLE users (id serial PRIMARY KEY,username VARCHAR ( 50 ) UNIQUE NOT NULL,city VARCHAR ( 50 ) NOT NULL,email VARCHAR ( 255 ) UNIQUE NOT NULL);

Creating the database connections and handler functions:

  1. In the myapp directory, create a main.go file, the directory structure should currently be as follows:
$ touch main.go$ ls -altotal 0drwxr-xr-x  4 eomolo  staff  128 Mar 20 17:04 .drwxr-xr-x  7 eomolo  staff  224 Mar 20 16:43 ..-rw-r--r--  1 eomolo  staff   22 Mar 20 17:04 go.mod-rw-r--r--  1 eomolo  staff    0 Mar 20 17:01 main.go

2. It’s best practice not to expose your database credentials in your code. Use an environment variable to make them accessible. Create a .env file:

$ cat .envDBUSER="your db user"DBPASS="your db pass"DBNAME=myappDBHOST=localhostDBPORT=5432

3. In your directory, create your main.go file then import the following packages:

  1. database/sql — a generic interface around SQL (or SQL-like) databases
  2. fmt — a package that implements formatted I/O
  3. log — a simple logging package
  4. os — an interface to operating system functionality
  5. godotenv — loads env vars from a .env file
#install the package$ go get github.com/joho/godotenv

6. pq — a pure Go Postgres driver for the database/sql package.

#install the package$ go get github.com/lib/pq

To test whether database connection can be successfully achieved, configure your main .go file similarly to the following:

The database driver pq must be imported with _ character in front of the import statement. It’s because we don’t use it explicitly in the code meanwhile it’s still required by database/sql package.

Run the command `go run main.go` to compile and run the main package. Barring any syntax, configuration, or incorrect credential issues, the string ‘Connected!’ will be returned:

$ go run main.go
Connected!

In the next part article, we’ll cover CRUD operations using a front-end interface to handle them.

--

--