Como Criar uma API REST com Golang e Gin (Guia Completo 2026)

Neste tutorial, você vai aprender a criar uma API REST completa em Golang usando o Gin Framework, do zero até o deploy.

O que vamos construir

Uma API de gerenciamento de tarefas (Todo List) com:

  • ✅ CRUD completo (Create, Read, Update, Delete)
  • ✅ Validação de dados
  • ✅ Middleware de logging
  • ✅ Documentação com Swagger
  • ✅ Docker para deploy

Pré-requisitos

  • Go 1.21+ instalado
  • Conhecimento básico de HTTP e REST
  • Editor de código (VS Code recomendado)

Passo 1: Inicializar o Projeto

mkdir todo-api && cd todo-api
go mod init github.com/seuusuario/todo-api
go get github.com/gin-gonic/gin

Passo 2: Estrutura de Pastas

todo-api/
├── cmd/
│   └── server/
│       └── main.go
├── internal/
│   ├── handlers/
│   │   └── todo.go
│   ├── models/
│   │   └── todo.go
│   └── storage/
│       └── memory.go
├── go.mod
└── Dockerfile

Passo 3: Definir o Modelo

Crie internal/models/todo.go:

package models

type Todo struct {
    ID          string `json:"id"`
    Title       string `json:"title" binding:"required"`
    Description string `json:"description"`
    Completed   bool   `json:"completed"`
    CreatedAt   string `json:"created_at"`
}

Passo 4: Implementar o Storage

Crie internal/storage/memory.go:

package storage

import (
    "sync"
    "github.com/seuusuario/todo-api/internal/models"
)

type MemoryStorage struct {
    mu    sync.RWMutex
    todos map[string]models.Todo
}

func New() *MemoryStorage {
    return &MemoryStorage{
        todos: make(map[string]models.Todo),
    }
}

func (s *MemoryStorage) Create(todo models.Todo) models.Todo {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.todos[todo.ID] = todo
    return todo
}

func (s *MemoryStorage) GetAll() []models.Todo {
    s.mu.RLock()
    defer s.mu.RUnlock()
    todos := make([]models.Todo, 0, len(s.todos))
    for _, t := range s.todos {
        todos = append(todos, t)
    }
    return todos
}

Passo 5: Criar os Handlers

Crie internal/handlers/todo.go:

package handlers

import (
    "net/http"
    "github.com/gin-gonic/gin"
    "github.com/google/uuid"
    "github.com/seuusuario/todo-api/internal/models"
    "github.com/seuusuario/todo-api/internal/storage"
)

type TodoHandler struct {
    store *storage.MemoryStorage
}

func NewTodoHandler(store *storage.MemoryStorage) *TodoHandler {
    return &TodoHandler{store: store}
}

func (h *TodoHandler) CreateTodo(c *gin.Context) {
    var todo models.Todo
    if err := c.ShouldBindJSON(&todo); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    
    todo.ID = uuid.New().String()
    h.store.Create(todo)
    
    c.JSON(http.StatusCreated, todo)
}

func (h *TodoHandler) GetTodos(c *gin.Context) {
    todos := h.store.GetAll()
    c.JSON(http.StatusOK, todos)
}

Passo 6: Configurar o Servidor

Crie cmd/server/main.go:

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/seuusuario/todo-api/internal/handlers"
    "github.com/seuusuario/todo-api/internal/storage"
)

func main() {
    store := storage.New()
    todoHandler := handlers.NewTodoHandler(store)
    
    r := gin.Default()
    
    // Middleware
    r.Use(gin.Logger())
    r.Use(gin.Recovery())
    
    // Routes
    api := r.Group("/api/v1")
    {
        api.POST("/todos", todoHandler.CreateTodo)
        api.GET("/todos", todoHandler.GetTodos)
    }
    
    r.Run(":8080")
}

Passo 7: Testar a API

go run cmd/server/main.go

Teste com curl:

# Criar tarefa
curl -X POST http://localhost:8080/api/v1/todos \
  -H "Content-Type: application/json" \
  -d '{"title": "Aprender Golang", "description": "Estudar Gin framework"}'

# Listar tarefas
curl http://localhost:8080/api/v1/todos

Passo 8: Dockerizar

Crie o Dockerfile:

FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o /todo-api ./cmd/server

FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /todo-api /usr/local/bin/
EXPOSE 8080
CMD ["todo-api"]

Build e execute:

docker build -t todo-api .
docker run -p 8080:8080 todo-api

Próximos Passos

  1. Adicionar banco de dados (PostgreSQL com GORM)
  2. Implementar autenticação JWT
  3. Adicionar testes unitários
  4. Configurar CI/CD com GitHub Actions

Conclusão

Você agora tem uma API REST funcional em Golang com Gin! O código completo está disponível no GitHub.

Recursos Adicionais


Gostou do tutorial? Compartilhe no Twitter e junte-se à nossa comunidade no Telegram!