Creating RESTFUL API using Golang and Postgres Part 1

Cavdy
3 min readJan 19, 2020

--

Image from Google search

Hello Gophers, In this article we are going to create a restful API in Golang and Postgres.

I am writing this tutorial with the mind you already know how to write Golang, so I will be going straight to the point. Let’s get started

Let’s create a folder in our go -> src -> github.com -> profile to keep it organized. So I have created a new folder called go_db.

In the folder let initialize go mod, go mod is our package manager like package.json in NodeJs. So we initialize go mod by typing go mod init in our terminal. Then we create our main.go file in the root directory and setup our router, I am using *Gin Gonic*.
Here is my article on how to set up a router on Golang.

package mainimport ("log""os""github.com/gin-gonic/gin"routes "github.com/cavdy-play/go_db/routes")func main() {// Init Routerrouter := gin.Default()// Route Handlers / Endpointsroutes.Routes(router)log.Fatal(router.Run(":4747"))}

In my article where I showed you how to set up a router in Golang, I created our routes in the main.go file but in this tutorial, I am using the MVC pattern to keep things simple and neat. In the code above, I imported routes from an unknown directory because the directory does not exist yet, that is where our routes will be.

So let’s create a folder called routes and create a new file in it called routes.go

package routesimport ("net/http""github.com/gin-gonic/gin")
func Routes(router *gin.Engine) {router.GET("/", welcome)}
func welcome(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"status": 200,"message": "Welcome To API",})return}

So we have set up our basic router, now we can run go run main.go to start up our server and visit localhost:4747 to see our API response.

Here is the response from the postman

Our app is running now, now let’s integrate Postgres

We are going to use *Go PG* package, it helps connect Postgres to our app. So let’s bring the Go PG package

go get -u github.com/go-pg/pg

Now let’s create a new folder called configs and a new file in the config folder called db.go

package configimport ("log""os""github.com/go-pg/pg/v9")// Connecting to dbfunc Connect() *pg.DB {opts := &pg.Options{User: "db_username",Password: "db_password",Addr: "localhost:5432",Database: "db_dbname",}var db *pg.DB = pg.Connect(opts)if db == nil {log.Printf("Failed to connect")os.Exit(100)}log.Printf("Connected to db")return db}

This is our database configuration, if you read the Go_PG Documentation, this is how to configure the Postgres database.

In our main.go file, we need to call DB function to connect our database, let’s import our config package before or after routes import

models "github.com/cavdy-play/go_db/config"

and in the main.go file, before our router initialization, let call our Connect function.

config.Connect()

Now we have called our DB Connect function, let’s stop our server and start it again, we should see “Connected to db” or “Failed to connect”. It should only fail if your database details are wrong.

In the next tutorial, we will implement the CRUD of our app. Here is the part 2

--

--