Saltar a contenido

Go - Entorno de Desarrollo

Guía completa para configurar un entorno de desarrollo Go para backend que permita a Claude Code trabajar eficazmente.

Requisitos del Sistema

Componente Versión Mínima Recomendada
Go 1.21 1.22+
VS Code 1.80+ Latest
GoLand 2023.3+ Latest

Instalación de Go

Windows

# Winget
winget install GoLang.Go

# Verificar
go version

# Configurar GOPATH (si es necesario)
$env:GOPATH = "$env:USERPROFILE\go"
$env:PATH += ";$env:GOPATH\bin"

# Añadir permanentemente al PATH
[Environment]::SetEnvironmentVariable("GOPATH", "$env:USERPROFILE\go", "User")
[Environment]::SetEnvironmentVariable("PATH", "$env:PATH;$env:USERPROFILE\go\bin", "User")

macOS

# Homebrew
brew install go

# Configurar en ~/.zshrc
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin

# Verificar
go version

Linux

# Descargar e instalar
wget https://go.dev/dl/go1.22.0.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.22.0.linux-amd64.tar.gz

# Añadir a ~/.bashrc
export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin

source ~/.bashrc

# Verificar
go version

Herramientas Esenciales

Herramientas Integradas

# Formateo de código (incluido en Go)
go fmt ./...

# Análisis estático
go vet ./...

# Documentación
go doc fmt.Println
godoc -http=:6060  # Servidor de documentación local

Herramientas Recomendadas

# golangci-lint - Linter completo (RECOMENDADO)
# Windows
winget install GolangCI.golangci-lint

# macOS
brew install golangci-lint

# Linux
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.56.2

# Verificar
golangci-lint --version

# Ejecutar
golangci-lint run
# Air - Hot reload para desarrollo
go install github.com/air-verse/air@latest

# Inicializar configuración
air init

# Ejecutar con hot reload
air

# Configuración .air.toml
# root = "."
# tmp_dir = "tmp"
# [build]
#   cmd = "go build -o ./tmp/main ."
#   bin = "./tmp/main"
# migrate - Migraciones de base de datos
go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest

# Crear migración
migrate create -ext sql -dir migrations -seq create_users_table

# Aplicar migraciones
migrate -path migrations -database "postgres://user:pass@localhost:5432/db?sslmode=disable" up

# Revertir
migrate -path migrations -database "postgres://user:pass@localhost:5432/db?sslmode=disable" down 1
# swag - Generador de Swagger
go install github.com/swaggo/swag/cmd/swag@latest

# Generar documentación
swag init
# mockgen - Generador de mocks
go install go.uber.org/mock/mockgen@latest

# Generar mock
mockgen -source=interfaces.go -destination=mocks/mock_interfaces.go

IDE y Extensiones

Visual Studio Code

# Extensión oficial de Go
code --install-extension golang.go

# Extensiones adicionales recomendadas
code --install-extension mtxr.sqltools
code --install-extension mtxr.sqltools-driver-pg
code --install-extension ms-azuretools.vscode-docker

settings.json recomendado:

{
  "go.useLanguageServer": true,
  "go.lintTool": "golangci-lint",
  "go.lintFlags": ["--fast"],
  "go.formatTool": "goimports",
  "go.testFlags": ["-v"],
  "editor.formatOnSave": true,
  "[go]": {
    "editor.codeActionsOnSave": {
      "source.organizeImports": "explicit"
    }
  },
  "gopls": {
    "ui.semanticTokens": true,
    "analyses": {
      "unusedparams": true,
      "shadow": true
    }
  }
}

GoLand (JetBrains)

# Windows
winget install JetBrains.GoLand

# macOS
brew install --cask goland

# Incluye soporte nativo para:
# - Debugging
# - Refactoring
# - Database tools
# - Docker

Frameworks Web

# Instalar
go get -u github.com/gin-gonic/gin

# Estructura típica
myapp/
├── cmd/
   └── api/
       └── main.go
├── internal/
   ├── handler/
   ├── service/
   ├── repository/
   └── model/
├── pkg/
   └── config/
├── migrations/
├── go.mod
└── go.sum

# Ejemplo main.go
package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{"message": "pong"})
    })
    r.Run(":8080")
}

Echo (Alto rendimiento)

go get github.com/labstack/echo/v4

Fiber (Express-like)

go get github.com/gofiber/fiber/v2

Chi (Minimalista)

go get github.com/go-chi/chi/v5

ORM y Bases de Datos

# Instalar GORM
go get -u gorm.io/gorm

# Driver PostgreSQL
go get -u gorm.io/driver/postgres

# Driver MySQL
go get -u gorm.io/driver/mysql

# Driver SQLite
go get -u gorm.io/driver/sqlite

# Ejemplo de uso
package main

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

type User struct {
    gorm.Model
    Name  string
    Email string `gorm:"unique"`
}

func main() {
    dsn := "host=localhost user=postgres password=pass dbname=mydb port=5432 sslmode=disable"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    // Auto Migrate
    db.AutoMigrate(&User{})
}

sqlx (SQL puro con helpers)

go get github.com/jmoiron/sqlx

# Driver PostgreSQL
go get github.com/lib/pq

pgx (Driver PostgreSQL nativo)

go get github.com/jackc/pgx/v5

Ent (ORM con generación de código)

go get entgo.io/ent/cmd/ent

# Inicializar
go run entgo.io/ent/cmd/ent init User

# Generar código
go generate ./ent

Testing

Testing Nativo

# Ejecutar tests
go test ./...

# Con verbose
go test -v ./...

# Con cobertura
go test -cover ./...
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

# Tests específicos
go test -run TestUserCreate ./...

# Benchmark
go test -bench=. ./...

# Race detector
go test -race ./...

Testify (Assertions y Mocks)

go get github.com/stretchr/testify

# Ejemplo
package mypackage

import (
    "testing"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

func TestSomething(t *testing.T) {
    assert.Equal(t, 123, 123, "they should be equal")
    require.NotNil(t, object)  // Falla inmediatamente si nil
}

gomock

go install go.uber.org/mock/mockgen@latest

# Generar mocks
mockgen -source=interfaces.go -destination=mocks/mock_interfaces.go -package=mocks

Configuración de Proyecto

go.mod

# Inicializar módulo
go mod init github.com/myuser/myapp

# Descargar dependencias
go mod download

# Limpiar dependencias no usadas
go mod tidy

# Ver dependencias
go list -m all

# Actualizar dependencias
go get -u ./...

Estructura Recomendada

myapp/
├── cmd/
│   └── api/
│       └── main.go           # Entry point
├── internal/                  # Código privado
│   ├── config/
│   │   └── config.go
│   ├── handler/              # HTTP handlers
│   │   └── user_handler.go
│   ├── service/              # Business logic
│   │   └── user_service.go
│   ├── repository/           # Data access
│   │   └── user_repository.go
│   ├── model/                # Domain models
│   │   └── user.go
│   └── middleware/
│       └── auth.go
├── pkg/                      # Código público/reutilizable
│   ├── logger/
│   └── validator/
├── api/                      # OpenAPI specs
│   └── openapi.yaml
├── migrations/
│   ├── 000001_create_users.up.sql
│   └── 000001_create_users.down.sql
├── scripts/
├── Dockerfile
├── docker-compose.yml
├── Makefile
├── go.mod
└── go.sum

Makefile

.PHONY: build run test lint migrate

# Variables
APP_NAME=myapp
BUILD_DIR=./bin

# Build
build:
    go build -o $(BUILD_DIR)/$(APP_NAME) ./cmd/api

# Run
run:
    go run ./cmd/api

# Development with hot reload
dev:
    air

# Tests
test:
    go test -v -cover ./...

test-coverage:
    go test -coverprofile=coverage.out ./...
    go tool cover -html=coverage.out -o coverage.html

# Lint
lint:
    golangci-lint run

# Migrations
migrate-up:
    migrate -path migrations -database "$(DATABASE_URL)" up

migrate-down:
    migrate -path migrations -database "$(DATABASE_URL)" down 1

migrate-create:
    migrate create -ext sql -dir migrations -seq $(name)

# Swagger
swagger:
    swag init -g cmd/api/main.go

# Docker
docker-build:
    docker build -t $(APP_NAME) .

docker-run:
    docker run -p 8080:8080 $(APP_NAME)

# Clean
clean:
    rm -rf $(BUILD_DIR)
    rm -f coverage.out coverage.html

Docker para Go

Dockerfile Multi-stage

# Build stage
FROM golang:1.22-alpine AS builder

WORKDIR /app

# Copiar go.mod y go.sum primero (para cache)
COPY go.mod go.sum ./
RUN go mod download

# Copiar código fuente
COPY . .

# Build con flags de optimización
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o /app/main ./cmd/api

# Runtime stage
FROM alpine:3.19

RUN apk --no-cache add ca-certificates tzdata

WORKDIR /app

COPY --from=builder /app/main .
COPY --from=builder /app/migrations ./migrations

# Usuario no-root
RUN adduser -D -g '' appuser
USER appuser

EXPOSE 8080

CMD ["./main"]

Docker Compose

version: '3.8'

services:
  api:
    build: .
    ports:
      - "8080:8080"
    environment:
      - DATABASE_URL=postgres://postgres:postgres@db:5432/myapp?sslmode=disable
      - REDIS_URL=redis://redis:6379
    depends_on:
      - db
      - redis

  db:
    image: postgres:16
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: myapp
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

volumes:
  postgres_data:

Comandos que Claude Code Ejecutará

# Módulos
go mod init <module-name>
go mod tidy
go mod download
go get <package>

# Build y ejecución
go build ./...
go build -o bin/app ./cmd/api
go run ./cmd/api
air  # Hot reload

# Testing
go test ./...
go test -v -cover ./...
go test -race ./...
go test -bench=. ./...

# Formateo y linting
go fmt ./...
go vet ./...
golangci-lint run

# Migraciones
migrate create -ext sql -dir migrations -seq <name>
migrate -path migrations -database "$DATABASE_URL" up
migrate -path migrations -database "$DATABASE_URL" down 1

# Generación de código
go generate ./...
swag init
mockgen -source=<file> -destination=mocks/<file>

# Documentación
go doc <package>
godoc -http=:6060

Verificación del Entorno

#!/bin/bash
# verify-go-env.sh

echo "=== Verificación Entorno Go ==="

echo -e "\n--- Go ---"
go version

echo -e "\n--- GOPATH ---"
echo $GOPATH

echo -e "\n--- Herramientas instaladas ---"
which air && air -v || echo "air no encontrado"
which golangci-lint && golangci-lint --version || echo "golangci-lint no encontrado"
which migrate && migrate -version || echo "migrate no encontrado"
which swag && swag --version || echo "swag no encontrado"
which mockgen && mockgen --version || echo "mockgen no encontrado"

echo -e "\n--- PostgreSQL Client ---"
psql --version 2>/dev/null || echo "psql no encontrado"

echo -e "\n=== Verificación Completa ==="

Troubleshooting

"go: module not found"

# Verificar que go.mod existe
cat go.mod

# Inicializar si no existe
go mod init github.com/user/project

# Descargar dependencias
go mod tidy

Problemas con CGO

# Deshabilitar CGO si no es necesario
CGO_ENABLED=0 go build ./...

# O instalar compilador C
# Windows: instalar mingw-w64
# Linux: sudo apt install gcc

"cannot find package" en vendor

# Usar vendor
go mod vendor

# Build con vendor
go build -mod=vendor ./...

Recursos