项目文件夹

文件
T
Asim Aslam c26d74a8a1 Add CRUD, pub/sub, and API gateway templates; update AI features (#2909)
* feat(website): redesign docs and blog layouts, add blog header images

Redesign both layouts to match the new landing page:
- Consistent nav bar with logo, Docs, Blog, GitHub, Reference, Home
- Consistent footer with copyright and links
- CSS custom properties for theming
- Updated typography, spacing, and code block styling
- Active sidebar link highlighting in docs
- Dark mode support preserved

Generate 4 blog header images via Atlas Cloud:
- blog-deploy.png for post 1 (micro deploy)
- blog-mcp.png for posts 2, 3, 7 (MCP-related)
- blog-agents-demo.png for post 4 (agents demo)
- blog-dx.png for post 5 (DX cleanup)
- Reuse data-model.png for post 6 (model package)

All 7 existing blog posts now have header images.

* fix(website): prevent horizontal scroll on mobile landing page

Add overflow-x: hidden on html and body. Set max-width: 100% and
height: auto on all section and two-col images. Add overflow:
hidden to .two-col grid. Constrain hero pre with max-width and
overflow-x. Reduce font sizes and padding at mobile breakpoint.

* feat(website): add images to remaining core doc pages

Generate 5 more images via Atlas Cloud for docs:
- registry.png: service discovery diagram
- broker.png: pub/sub message broker pattern
- transport.png: multi-transport layers (HTTP, gRPC, NATS)
- config.png: dynamic configuration from multiple sources
- observability.png: monitoring dashboard with metrics/traces

Add images to registry.md, broker.md, transport.md, config.md,
observability.md, and architecture.md. All 11 main doc pages
now have header images.

* feat: add sponsor logos to landing page, README images, and flows blog post

Add Anthropic and Atlas Cloud sponsor logos to the landing page
with links to their respective blog posts. Logos display at 0.7
opacity with hover effect.

Add architecture and MCP agent images to the GitHub README for
the Overview and MCP sections.

Write blog post 9: "From Chat to Flows" — explores the concept
of LLM-powered service orchestration. Compares micro chat's
interactive model with persistent event-driven flows, shows how
the existing building blocks (ai/tools, History, broker) could
compose into a flow engine, discusses tradeoffs vs traditional
orchestration (Step Functions, Temporal), and includes a working
15-line code example. Explicitly positions it as a concept for
community feedback, not an announcement.

* feat(website): add animated hero video to landing page

Generate a 6-second hero video via Atlas Cloud's image-to-video
API (gemini-omni-flash). Shows the microservices network diagram
animating with data flowing between nodes.

Replace the static hero image with an autoplay muted looping
video element. Falls back to the static image via poster
attribute and img fallback for browsers without video support.

* feat(ai): add VideoModel interface with Atlas Cloud provider

Add ai.VideoModel interface for video generation alongside Model
and ImageModel. Supports text-to-video and image-to-video via
VideoRequest with prompt, reference images, duration, aspect
ratio, and resolution fields.

Implement GenerateVideo for Atlas Cloud using their async API:
POST /api/v1/model/generateVideo → poll /api/v1/model/prediction.
Default model is gemini-omni-flash image-to-video. Polls every
5 seconds until completion or context cancellation.

Register Atlas Cloud as a video provider via ai.RegisterVideo.
Add 3 tests: registration, no-key error, compile-time interface
check. Update ai/README.md with VideoModel docs.

The ai package now covers all three modalities:
- Model (text) — 7 providers
- ImageModel (image) — 2 providers (Atlas Cloud, OpenAI)
- VideoModel (video) — 1 provider (Atlas Cloud)

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-29 15:52:35 +01:00

16 KiB

Go Micro Go.Dev reference Go Report Card

Go Micro is a framework for distributed systems development.

Sponsors

    

Overview

Go Micro microservices architecture

Go Micro provides the core requirements for distributed systems development including RPC and Event driven communication. The Go Micro philosophy is sane defaults with a pluggable architecture. We provide defaults to get you started quickly but everything can be easily swapped out.

Features

Go Micro abstracts away the details of distributed systems. Here are the main features.

  • Authentication - Auth is built in as a first class citizen. Authentication and authorization enable secure zero trust networking by providing every service an identity and certificates. This additionally includes rule based access control.

  • Dynamic Config - Load and hot reload dynamic config from anywhere. The config interface provides a way to load application level config from any source such as env vars, file, etcd. You can merge the sources and even define fallbacks.

  • Data Storage - A simple data store interface to read, write and delete records. It includes support for many storage backends in the plugins repo. State and persistence becomes a core requirement beyond prototyping and Micro looks to build that into the framework.

  • Data Model - A typed data model layer with CRUD operations, queries, and multiple backends (memory, SQLite, Postgres). Define Go structs with tags and get type-safe Create/Read/Update/Delete/List/Count operations. Accessible via service.Model() alongside service.Client() and service.Server() for a complete service experience: call services, handle requests, save and query data.

  • Service Discovery - Automatic service registration and name resolution. Service discovery is at the core of micro service development. When service A needs to speak to service B it needs the location of that service. The default discovery mechanism is multicast DNS (mdns), a zeroconf system.

  • Load Balancing - Client side load balancing built on service discovery. Once we have the addresses of any number of instances of a service we now need a way to decide which node to route to. We use random hashed load balancing to provide even distribution across the services and retry a different node if there's a problem.

  • Message Encoding - Dynamic message encoding based on content-type. The client and server will use codecs along with content-type to seamlessly encode and decode Go types for you. Any variety of messages could be encoded and sent from different clients. The client and server handle this by default. This includes protobuf and json by default.

  • RPC Client/Server - RPC based request/response with support for bidirectional streaming. We provide an abstraction for synchronous communication. A request made to a service will be automatically resolved, load balanced, dialled and streamed.

  • Async Messaging - PubSub is built in as a first class citizen for asynchronous communication and event driven architectures. Event notifications are a core pattern in micro service development. The default messaging system is a HTTP event message broker.

  • MCP Integration - An MCP gateway you can integrate as a library, server or CLI command which automatically exposes services as tools for agents or other AI applications. Every service/endpoint get's converted into a callable tool.

  • Multi-Service Binaries - Run multiple services in a single process with isolated state per service. Start as a modular monolith, split into separate deployments when you need independent scaling. Each service gets its own server, client, and store while sharing the registry and broker for inter-service communication.

  • Pluggable Interfaces - Go Micro makes use of Go interfaces for each distributed system abstraction. Because of this these interfaces are pluggable and allows Go Micro to be runtime agnostic. You can plugin any underlying technology.

Getting Started

To make use of Go Micro

go get go-micro.dev/v5@v5.16.0

Create a service and register a handler

package main

import (
        "go-micro.dev/v5"
)

type Request struct {
        Name string `json:"name"`
}

type Response struct {
        Message string `json:"message"`
}

type Say struct{}

func (h *Say) Hello(ctx context.Context, req *Request, rsp *Response) error {
        rsp.Message = "Hello " + req.Name
        return nil
}

func main() {
        // create the service
        service := micro.New("helloworld")

        // register handler
        service.Handle(new(Say))

        // run the service
        service.Run()
}

Set a fixed address

service := micro.New("helloworld", micro.Address(":8080"))

Call it via curl

curl -XPOST \
     -H 'Content-Type: application/json' \
     -H 'Micro-Endpoint: Say.Hello' \
     -d '{"name": "alice"}' \
      http://localhost:8080

MCP & AI Agents

AI agent calling microservices via MCP

Go Micro is designed for an agent-first workflow. Every service you build automatically becomes a tool that AI agents can discover and use via the Model Context Protocol (MCP).

Services as Tools

Write a normal Go Micro service and it's instantly available as an MCP tool:

// SayHello greets a person by name.
// @example {"name": "Alice"}
func (g *GreeterService) SayHello(ctx context.Context, req *HelloRequest, rsp *HelloResponse) error {
    rsp.Message = "Hello " + req.Name
    return nil
}

Run with micro run and the agent playground and MCP tools registry are ready:

micro run
# Agent Playground:  http://localhost:8080/agent
# MCP Tools:         http://localhost:8080/mcp/tools

Use micro mcp serve for local AI tools like Claude Code, or connect any MCP-compatible agent to the HTTP endpoint.

micro chat

For an interactive terminal session that lets you talk to your services through an LLM:

ANTHROPIC_API_KEY=sk-ant-... micro chat --provider anthropic
> list all users
> create an order for product 42

micro chat discovers every service in the registry, exposes each endpoint as a tool, and lets the model orchestrate calls. The same building blocks (ai/tools) work from your own services:

import "go-micro.dev/v5/ai/tools"

set := tools.New(service.Registry())
discovered, _ := set.Discover()

m := ai.New("anthropic",
    ai.WithAPIKey(key),
    ai.WithToolHandler(set.Handler(service.Client())),
)
resp, _ := m.Generate(ctx, &ai.Request{
    Prompt: userInput,
    Tools:  discovered,
})

See the MCP guide for authentication, scopes, and advanced usage.

Multi-Service Binaries

Run multiple services in a single binary — start as a modular monolith, split into separate deployments later when you actually need to.

users := micro.New("users", micro.Address(":9001"))
orders := micro.New("orders", micro.Address(":9002"))

users.Handle(new(Users))
orders.Handle(new(Orders))

// Run all services together with shared lifecycle
g := micro.NewGroup(users, orders)
g.Run()

Each service gets its own server, client, store, and cache while sharing the registry, broker, and transport — so they can discover and call each other within the same process.

See the multi-service example for a working demo.

Data Model

Go Micro includes a typed data model layer for persistence. Define a struct, tag a key field, and get type-safe CRUD and query operations backed by memory, SQLite, or Postgres.

import (
        "go-micro.dev/v5/model"
        "go-micro.dev/v5/model/sqlite"
)

// Define your data type
type User struct {
        ID    string `json:"id" model:"key"`
        Name  string `json:"name"`
        Email string `json:"email" model:"index"`
        Age   int    `json:"age"`
}

Register your types and use the model:

service := micro.New("users")

// Register and use the service's model backend
db := service.Model()
db.Register(&User{})

// CRUD operations
db.Create(ctx, &User{ID: "1", Name: "Alice", Email: "alice@example.com", Age: 30})

user := &User{}
db.Read(ctx, "1", user)

user.Name = "Alice Smith"
db.Update(ctx, user)

db.Delete(ctx, "1", &User{})

Query with filters, ordering, and pagination:

var results []*User

// Find users by field
db.List(ctx, &results, model.Where("email", "alice@example.com"))

// Complex queries
db.List(ctx, &results,
        model.WhereOp("age", ">=", 18),
        model.OrderDesc("name"),
        model.Limit(10),
        model.Offset(20),
)

count, _ := users.Count(ctx, model.Where("age", 30))

Swap backends with an option:

// Development: in-memory (default)
service := micro.New("users")

// Production: SQLite or Postgres
db, _ := sqlite.New(model.WithDSN("file:app.db"))
service := micro.New("users", micro.Model(db))

Every service gets Client(), Server(), and Model() — call services, handle requests, and save data all from the same interface.

Examples

Check out /examples for runnable code:

See all examples for more.

Protobuf

Install the code generator and see usage in the docs:

go install go-micro.dev/v5/cmd/protoc-gen-micro@v5.16.0

Note: Use a specific version instead of @latest to avoid module path conflicts. See releases for the latest version.

Docs: internal/website/docs/getting-started.md

Command Line

Install the CLI:

go install go-micro.dev/v5/cmd/micro@v5.16.0

Note: Use a specific version instead of @latest to avoid module path conflicts. See releases for the latest version.

Quick Start

micro new helloworld   # Create a new service
cd helloworld
micro run              # Run with API gateway and hot reload

Then open http://localhost:8080 to see your service and call it from the browser.

Development Workflow

Stage Command Purpose
Develop micro run Local dev with hot reload and API gateway
Build micro build Compile production binaries
Deploy micro deploy Push to a remote Linux server via SSH + systemd
Dashboard micro server Optional production web UI with JWT auth

micro run

micro run starts your services with:

  • Web Dashboard - Browse and call services at /
  • Agent Playground - AI chat with MCP tools at /agent
  • API Explorer - Browse endpoints and schemas at /api
  • API Gateway - HTTP to RPC proxy at /api/{service}/{method} (no auth in dev mode)
  • MCP Tools - Services as AI tools at /mcp/tools
  • Health Checks - Aggregated health at /health
  • Hot Reload - Auto-rebuild on file changes

Note: micro run and micro server use a unified gateway architecture. See Gateway Architecture for details.

micro run                    # Gateway on :8080
micro run --address :3000    # Custom gateway port
micro run --no-gateway       # Services only
micro run --env production   # Use production environment

Configuration

For multi-service projects, create a micro.mu file:

service users
    path ./users
    port 8081

service posts
    path ./posts
    port 8082
    depends users

env development
    DATABASE_URL sqlite://./dev.db

The gateway runs on :8080 by default, so services should use other ports.

Deployment

Deploy to any Linux server with systemd:

# On your server (one-time setup)
curl -fsSL https://go-micro.dev/install.sh | sh
sudo micro init --server

# From your laptop
micro deploy user@your-server

The deploy command:

  1. Builds binaries for Linux
  2. Copies via SSH to the server
  3. Sets up systemd services
  4. Verifies services are healthy

Optionally run micro server on the deployed machine for a production web dashboard with JWT auth, user management, and API explorer.

Manage deployed services:

micro status --remote user@server    # Check status
micro logs --remote user@server      # View logs
micro logs myservice --remote user@server -f  # Follow specific service

No Docker required. No Kubernetes. Just systemd.

See internal/website/docs/deployment.md for full deployment guide.

See cmd/micro/README.md for full CLI documentation.

Docs: internal/website/docs

Package reference: https://pkg.go.dev/go-micro.dev/v5

User Guides:

Architecture & Performance:

Security:

Supported AI Providers

Go Micro’s ai package gives every provider the same interface: Init, Generate, Stream, and functional options. Swap providers with a single import.

Provider Import Default Model
Anthropic go-micro.dev/v5/ai/anthropic claude-sonnet-4-20250514
Google Gemini go-micro.dev/v5/ai/gemini gemini-2.5-flash
Groq go-micro.dev/v5/ai/groq llama-3.3-70b-versatile
Mistral go-micro.dev/v5/ai/mistral mistral-large-latest
OpenAI go-micro.dev/v5/ai/openai gpt-4o
Together AI go-micro.dev/v5/ai/together Llama-3.3-70B-Instruct-Turbo
Atlas Cloud go-micro.dev/v5/ai/atlascloud llama-3.3-70b

Any provider that exposes an OpenAI-compatible API can also be used directly:

m := ai.New("openai",
    ai.WithAPIKey("your-key"),
    ai.WithBaseURL("https://api.yourprovider.com"),
)

Want to add your platform? See the AI Provider Integration Guide for how to implement ai.Model and submit a PR. We welcome both code contributions and sponsorships from AI infrastructure companies — reach out via a GitHub issue.

Adopters

  • Sourse - Work in the field of earth observation, including embedded Kubernetes running onboard aircraft, and we’ve built a mission management SaaS platform using Go Micro.