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:
phantodev.hashnode.dev/golang-api-postgres-..
GIT REPO: 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 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