Skip to main content

Command Palette

Search for a command to run...

GoLang API + Postgres for Beginners: Step 3

Updated
4 min read
GoLang API + Postgres for Beginners: Step 3
C

Eduardo Burko, aka Phantodev, i'm a skilled front-end developer with a focus on creating robust applications using the React framework. With extensive experience in implementing complex features, i create clean and organized code, ensuring his applications are scalable and easy to maintain. I'm a quick learner and proficient in other front-end technologies like HTML, CSS, and JavaScript, and back-end technologies like Node.js and Express. I have experience working with clients in various industries, developing custom solutions for them. I'm strength in communication and working in agile environments makes me flexible and adaptable to changing project requirements.

Hello guys... It's me again... Let's start the third lesson of this great tutorial for beginners. If you accidentally landed here and don't know where we started, read the post where we started our project at the following link:

https://phantodev.hashnode.dev/golang-api-postgres-for-beginners-step-1

GIT REPO: https://github.com/phantodev/api-with-go-postgres
BRANCH: step-1 - Lesson 01
BRANCH: step-2 - Lesson 02

Let's remember our structure

api-with-go-postgres/
├── database/
│   ├── connection.go
├── models/  <-- We add this folder in last lesson
│   ├── products.go <-- We add this file in last lesson
├── products/
│   ├── create_product.go <-- We change this file in last lesson
│   ├── delete_product_by_id.go
│   ├── update_product_by_id.go
│   ├── get_all_products.go
├── auth/
│   ├── forgot_password.go
│   ├── login.go
│   ├── reset_password.go
├── main.go <-- We change this file in last lesson

1º Step: Today we gonna change the get_all_products.go. We need to connect to postgres and gel all products from database. Imagine with me: Your front-end will have a page that will list all the products list, right? So, now open your get_all_products.go file and put the code below:

package products

import (
    "api-with-go-postgres/models"
    "database/sql"
    "encoding/json"
    "net/http"
)

func GetAllProducts(db *sql.DB) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // Execute SQL query to get all products from the database
        rows, err := db.Query("SELECT * FROM products")
        // Check if there was an error executing the query
        if err != nil {
            http.Error(w, "Error to get All Products in database", http.StatusInternalServerError)
            return
        }
        // Here we need to close the rows when we are done with them
        defer rows.Close()
        // Create a variable of model Products to store the products
        var products []models.Products
        // Iterate over the rows and store the products in the products variable
        for rows.Next() {
            var product models.Products
            // Scan the rows into the product variable
            if err := rows.Scan(&product.ID, &product.Name, &product.Description); err != nil {
                http.Error(w, "Error scanning product", http.StatusInternalServerError)
                return
            }
            // Append the product above in products list variabel
            products = append(products, product)
        }
        // Check if there was an error iterating over the rows
        if err := rows.Err(); err != nil {
            http.Error(w, "Error reading rows in Database", http.StatusInternalServerError)
            return
        }
        // Set the Content-Type header to application/json
        w.Header().Set("Content-Type", "application/json")
        // Set the status code to 200 OK
        w.WriteHeader(http.StatusOK)
        // Encode the products to JSON and write it to the response body
        if err := json.NewEncoder(w).Encode(products); err != nil {
            http.Error(w, "Error encoding products", http.StatusInternalServerError)
            return
        }
    }
}

2º Step: In the code above you need to pay attention to three points: First, understand how the SQL is being executed in the database. Second is to understand how the rows.Scan() method and the append() method work. And finally, understand how the return in Json format to the handler works with the json.NewEncoder() method.

If you understand how this process works, continue and you will be a great professional!

3º Step: We need to create a new route in our main.go file. Please check this line in code below: http.HandleFunc("/products/all", products.GetAllProducts(db))

package main

import (
    "api-with-go-postgres/database"
    "api-with-go-postgres/products"
    "log"
    "net/http"
)

func main() {
    // Variabel to store a Postregres connection
    db := database.Connect()

    // Route to call CreateProduct Controller
    http.HandleFunc("/products/create", products.CreateProduct(db))
    // NEW LINE BELOW: Route to call GetAllProducts Controller
    http.HandleFunc("/products/all", products.GetAllProducts(db))

    // Starting the server
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal("Error to start server in :8080", err)
    }
}

4º Step: Now, Next pass... let's run our program in terminal:

go run main.go

5º Step: I'm using a THUNDER CLIENT in VSCODE to test a REQUEST in my route. You just need send a GET REQUEST in http://localhost:8080/products/all

6º Step: If everything went well you should see a JSON of products list, when returning your request.

So that's it for today my friends. Follow the next steps here. We will learn how to create large, complete projects using Javascript technology for the Front-End and GoLang technology for the Back-End.

Next lesson we gonna learn how to delete a product from database.

GIT REPO: github.com/phantodev/api-with-go-postgres
BRANCH: step-3**

Eduardo Burko - Fullstack Developer

Get in touch in phantodev.com.br

You need a help? Call me in telegram @phantodev

More from this blog

Show me the code, Phantodev!

12 posts

I'm working with Front-End since to 2005 encompassing software development, architecture and UI Design. Get in Touch and let's work together? I'm open to work in new projects :-)