Project Overview
1. What You Will Build
You will construct a blog API with the following functionalities:
Registration with a username, email and password
Login with email and password
Create new post
Update post
Retrieve a particular post
Delete Post
2. Prerequisites
Before diving in, ensure you have the following prerequisites:
Go
Basic understanding of Go and JWTs
Postman
Git
psql
PostgreSQL installed on your machine
Project Setup
To initiate the project, follow these steps:
- Create a new folder named blog_api in your development directory and navigate into it.
mkdir blog_api
cd blog_api
- Initialize a Go module with the following command.
go mod init blog_api
This generates a go.mod file to track your project's dependencies.
- Install Dependencies
This project utilizes the gin framework. Run the following command to install gin and other dependencies we will be using
go get github.com/gin-gonic/gin
go get github.com/jinzhu/gorm
go get golang.org/x/crypto/bcrypt
github.com/golang-jwt/jwt/v5
Now create the following directories:
internal
internal/auth
internal/handler
internal/storage
internal/router
internal/model
config
Database
main.go
Connecting to Postgres
I am assuming that you have postgres installed already, if you dont go ahead and install it
create a database named blog_db
CREATE DATABASE blog_db;
In your config folder Create a .env file in your root directory to store our database details
config/.env
DB_DSN=host=localhost user=yourusername password= your_password dbname=blog_db port=5432 sslmode=disable
Creating models
create models for User
and Post
In your internal/model folder, create a user.go and a post.go file
Internal/model/user.go
package model
import "gorm.io/gorm"
type User struct {
Username string `gorm:"unique; not null"`
Email string `gorm:"unique; not null"`
Password string `gorm:"not null"`
Posts []Post `gorm:"foreignKey:AuthorID"`
}
internal/model/post..go
package model
import "gorm.io/gorm"
type Post struct {
gorm.Model
Title string `gorm:"not null"`
Content string `gorm:"not null"`
AuthorID uint
Author User `gorm:"foreignKey:AuthorID"`
}
Initializing Database
We will setup the database connection using Gorm. In your internal/storage folder, create a new file named database.go.
internal/storage/database.go
package storage
import (
"log"
"os"
"blog-api/internal/model"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
DB *gorm.DB
func InitDB()
{
dsn := os.Getenv("DB_DSN")
db, err := gorm.open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database", err)
}
db.Automigrate(&model.User{}, &model.Post{})
DB = db
}
In this code snippet:
DB is a global variable that holds the database connection.
InitDB initializes the database connection using the gorm.Open method and automatically migrates the User and Post models.
Now, set up main.go file to :
loads the .env file.
Initializes the database.
Sets up the router and starts the HTTP server.
package main
import (
"log"
"net/http"
"blog-api/internal/router"
"blog-api/internal/storage"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load("config/.env)
if err != nil {
log.Fatal("Error loading .env file)
}
//initialize database
storage.InitDB()
//setup router
r := router.setupRouter()
log.Fatal(http.ListenAndServe(":8080", r))
Note: The setupRouter is a function in our router.go that sets up our application router, feel free to comment it out, we will setup our router in the next part of the blog.
Run the Application
Run the application using the command
go run main.go
Top comments (0)