Building a Blog API with Golang using Gin and Gorm (Part 1)

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 pa…


This content originally appeared on DEV Community and was authored by Adetunji Adetayo

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:

  1. Create a new folder named blog_api in your development directory and navigate into it.
mkdir blog_api
cd blog_api
  1. 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.

  1. 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
}

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.

Eun the Application

Run the application using the command

go run main.go


This content originally appeared on DEV Community and was authored by Adetunji Adetayo


Print Share Comment Cite Upload Translate Updates
APA

Adetunji Adetayo | Sciencx (2024-08-22T22:58:43+00:00) Building a Blog API with Golang using Gin and Gorm (Part 1). Retrieved from https://www.scien.cx/2024/08/22/building-a-blog-api-with-golang-using-gin-and-gorm-part-1/

MLA
" » Building a Blog API with Golang using Gin and Gorm (Part 1)." Adetunji Adetayo | Sciencx - Thursday August 22, 2024, https://www.scien.cx/2024/08/22/building-a-blog-api-with-golang-using-gin-and-gorm-part-1/
HARVARD
Adetunji Adetayo | Sciencx Thursday August 22, 2024 » Building a Blog API with Golang using Gin and Gorm (Part 1)., viewed ,<https://www.scien.cx/2024/08/22/building-a-blog-api-with-golang-using-gin-and-gorm-part-1/>
VANCOUVER
Adetunji Adetayo | Sciencx - » Building a Blog API with Golang using Gin and Gorm (Part 1). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/22/building-a-blog-api-with-golang-using-gin-and-gorm-part-1/
CHICAGO
" » Building a Blog API with Golang using Gin and Gorm (Part 1)." Adetunji Adetayo | Sciencx - Accessed . https://www.scien.cx/2024/08/22/building-a-blog-api-with-golang-using-gin-and-gorm-part-1/
IEEE
" » Building a Blog API with Golang using Gin and Gorm (Part 1)." Adetunji Adetayo | Sciencx [Online]. Available: https://www.scien.cx/2024/08/22/building-a-blog-api-with-golang-using-gin-and-gorm-part-1/. [Accessed: ]
rf:citation
» Building a Blog API with Golang using Gin and Gorm (Part 1) | Adetunji Adetayo | Sciencx | https://www.scien.cx/2024/08/22/building-a-blog-api-with-golang-using-gin-and-gorm-part-1/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.