DEV Community

loading...

Golang, Vuejs and Tailwind Ecommerce website (Clasified ads) Part 1.

bajro17 profile image Bajro Updated on ・2 min read

Let's start!!!

I assume that you have Golang and Postgres installed and that you are not a complete beginner.

Most of the time, when I start with the Gofiber project, I starting with this repo from gofiber recipes Start template. It saves a lot of time, and it comes with a nice MVC organization of folders.
After we download this repository, we will change from gorm v1 to v2.

You will do it like this:

  1. Type in console go get -u gorm.io/driver/postgres
  2. Type in console go get -u gorm.io/gorm
  3. Make a copy of the .env.sample and rename it to .env and change it with your Postgres access.

The next step will be to change every file you find "github.com/jinzhu/gorm" to "gorm.io/gorm" and replace the content of the database/connect.go with this one:

package database

import (
    "api-fiber-gorm/config"
    "api-fiber-gorm/model"
    "fmt"
    "strconv"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

// ConnectDB connect to db
func ConnectDB() {
    var err error
    p := config.Config("DB_PORT")
    port, err := strconv.ParseUint(p, 10, 32)

    dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", config.Config("DB_HOST"), port, config.Config("DB_USER"), config.Config("DB_PASSWORD"), config.Config("DB_NAME"))

    DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})

    if err != nil {
        panic("failed to connect database")
    }

    fmt.Println("Connection Opened to Database")
    DB.AutoMigrate(&model.Product{}, &model.User{})
    fmt.Println("Database Migrated")
}
Enter fullscreen mode Exit fullscreen mode

The next step will be to go in handler/auth and import the "errors" package and change line 26 and 38 from

if gorm.IsRecordNotFoundError(err) {
...
Enter fullscreen mode Exit fullscreen mode

to gorm v2 syntax

if errors.Is(err, gorm.ErrRecordNotFound) { 
...
Enter fullscreen mode Exit fullscreen mode

After all this, we finally can start our project with

go run ./main.go
Enter fullscreen mode Exit fullscreen mode

I usually use Postman to test it, thanks to repo documentation. We have our collection ready to use for Postman.
Just visit this link Postman collection and import collection, and you can start testing.

Next time we will make our database with gorm make all models we need. Maybe we will add some models later, but this is all for today.

Discussion (0)

pic
Editor guide