GORM Setup for Go Web Application

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1 servicesAll 2065 services
GORM Setup for Go Web Application
Medium
~1 business day
FAQ

Our competencies:

Development stages

Latest works

  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1171
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1094
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    831
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    879
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    453

GORM Setup for Go Web Application

GORM is the most popular ORM for Go. It doesn't try to hide SQL completely, giving direct access to raw queries where needed. Version v2 is incompatible with v1 API-wise.

go get gorm.io/gorm
go get gorm.io/driver/postgres

Initialization

package db

import (
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
    "gorm.io/gorm/logger"
    "log"
    "time"
)

func New(dsn string) (*gorm.DB, error) {
    db, err := gorm.Open(postgres.New(postgres.Config{
        DSN:                  dsn,
        PreferSimpleProtocol: true,
    }), &gorm.Config{
        Logger:      logger.Default.LogMode(logger.Warn),
        NowFunc:    func() time.Time { return time.Now().UTC() },
    })

    sqlDB, _ := db.DB()
    sqlDB.SetMaxOpenConns(25)
    sqlDB.SetMaxIdleConns(10)
    sqlDB.SetConnMaxLifetime(5 * time.Minute)

    return db, err
}

Models

type Product struct {
    ID         uint           `gorm:"primarykey"`
    CreatedAt  time.Time
    UpdatedAt  time.Time
    DeletedAt  gorm.DeletedAt `gorm:"index"`

    Title      string        `gorm:"type:varchar(500);not null"`
    Slug       string        `gorm:"type:varchar(520);uniqueIndex"`
    Price      float64       `gorm:"type:decimal(12,2)"`
    Status     ProductStatus `gorm:"type:varchar(20);default:draft"`
    CategoryID uint          `gorm:"not null;index"`
    Category   Category      `gorm:"foreignKey:CategoryID;constraint:OnDelete:RESTRICT"`
    Tags       []Tag         `gorm:"many2many:product_tags;"`
}

func (Product) TableName() string {
    return "products"
}

Queries

type ProductRepository struct {
    db *gorm.DB
}

func (r *ProductRepository) GetPublished(
    ctx context.Context,
    categoryID uint,
    limit, offset int,
) ([]Product, error) {
    var products []Product
    err := r.db.WithContext(ctx).
        Preload("Category").
        Preload("Tags").
        Where("category_id = ? AND status = ?", categoryID, "published").
        Order("created_at DESC").
        Limit(limit).
        Offset(offset).
        Find(&products).Error
    return products, err
}

Migrations

Use golang-migrate for production:

go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest
migrate create -ext sql -dir migrations -seq create_products

Timeline

Initial GORM setup with golang-migrate: 1 day.