1. Writing CI to Build and Push Image to GHCR

.github/workflows/deploy-api-go.yml

name: Build & Push ( api-go ) Docker Image
on:
  push:
    branches: [main]
    # Only run when go backend changes
    paths:
      - "apps/api-go/**"
      - ".github/workflows/deploy-api-go.yml"

  workflow_dispatch: # Allow me to manually run this workflow from Github UI

# This controls what the GITHUB_TOKEN is allowed to do inside the workflow.
permissions:
  contents: read
  packages: write # Allows to push images to GHCR & publish packages

jobs:
  build-push:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Docker Login
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_PASSWORD }}

      - name: Setup Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Login to GHCR
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      # This action automatically generates image tags, labels, version metadata
      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v5
        with:
          # ghcr.io/RitikaxG/runstate-api-go ( Base Image )
          images: ghcr.io/${{ github.repository_owner }}/runstate-api-go
          tags: |
            type=raw,value=latest 
            type=sha
          # type=sha: this creates a tag based on the commit hash.

      - name: Build and Push
        uses: docker/build-push-action@v6
        with:
          context: .
          file: apps/api-go/Dockerfile
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}

          # Performance Optimisation
          # gha = GitHub Actions cache storage, 
          cache-from: type=gha  # Before building, try to restore cached layers from GitHub Actions.
          cache-to: type=gha,mode=max # After building, save all build layers to GitHub cache.

  

image.png

git checkout -b ci/pr-check

2. Adding Pre Commit Step

Step 1 : Create hooks folder

From repo root:

mkdir .githooks

Step 2 — Create pre-commit file

touch .githooks/pre-commit

Now open it in your editor and paste:

#!/bin/sh
echo"Running gofmt..."
cd apps/api-go ||exit1
gofmt-w .
git add .

Save.