go-migrationgo-migration
Framework Integration
Documentation

Gin

Integrate go-migration with the Gin web framework using only *sql.DB.

Gin Integration

go-migration works with Gin out of the box. Since go-migration depends only on *sql.DB, there are no framework-specific adapters or plugins to install.

go-migration is framework-agnostic. It only needs a *sql.DB connection — the same one your Gin application already uses.

Complete Example

This example shows a Gin application that runs migrations on startup and exposes a health-check endpoint.

Define a Migration

migrations/20240101_create_users_table.go
package migrations

import (
    "github.com/gopackx/go-migration/schema"
)

type CreateUsersTable struct{}

func (m *CreateUsersTable) Up(s *schema.Builder) {
    s.Create("users", func(bp *schema.Blueprint) {
        bp.ID("id")
        bp.String("name", 255)
        bp.String("email", 255).Unique()
        bp.Timestamp("created_at").Nullable()
        bp.Timestamp("updated_at").Nullable()
    })
}

func (m *CreateUsersTable) Down(s *schema.Builder) {
    s.DropIfExists("users")
}

Set Up the Database and Migrator

Open a *sql.DB connection, create the migrator, register migrations, and run them before starting Gin.

main.go
package main

import (
    "database/sql"
    "log"

    "github.com/gin-gonic/gin"
    _ "github.com/lib/pq"

    "github.com/gopackx/go-migration/migrator"
    "your-project/migrations"
)

func main() {
    // 1. Open a database connection
    db, err := sql.Open("postgres", "postgres://user:password@localhost:5432/mydb?sslmode=disable")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // 2. Create the migrator
    m := migrator.New(db)

    // 3. Register migrations
    m.Register("20240101_create_users_table", &migrations.CreateUsersTable{})

    // 4. Run pending migrations
    if err := m.Up(); err != nil {
        log.Fatal("migration failed: ", err)
    }
    log.Println("Migrations completed")

    // 5. Set up Gin
    r := gin.Default()

    r.GET("/health", func(c *gin.Context) {
        if err := db.Ping(); err != nil {
            c.JSON(500, gin.H{"status": "unhealthy"})
            return
        }
        c.JSON(200, gin.H{"status": "healthy"})
    })

    r.Run(":8080")
}

Run the Application

bash
go run main.go

Gin starts on port 8080 with all migrations applied. The /health endpoint confirms the database connection is active.

Key Takeaway

go-migration doesn't know or care about Gin. It receives a *sql.DB, runs migrations, and returns. You can call m.Up() at startup, in a CLI command, or anywhere else — the integration pattern is the same regardless of framework.

What's Next?