项目文件夹

文件
asim ee76eb6d2c v5.15.0: Unified Gateway Architecture + MCP Support
Major Features:
- Unified gateway architecture (micro run + micro server use same code)
- MCP (Model Context Protocol) integration as library package
- AI-accessible microservices with 3 lines of code

Gateway Unification:
- Created reusable gateway module (cmd/micro/server/gateway.go)
- Updated micro run to use unified gateway (removed duplicate code)
- Conditional authentication (disabled in dev, required in prod)
- Reduced code duplication, simplified maintenance

MCP Integration:
- New library package: gateway/mcp
- Automatic service discovery → MCP tools
- HTTP/SSE transport support (stdio coming soon)
- Works for both library users and CLI users
- CLI flags: --mcp-address for micro run and micro server

Documentation:
- ADR-010: Unified Gateway Architecture
- CLI & Gateway Guide for users
- MCP Gateway README and examples
- Blog post: Making Your Microservices AI-Native with MCP

Breaking Changes: None (fully backward compatible)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-11 10:40:48 +00:00

9.9 KiB

layout
layout
default

CLI & Gateway Guide

The Go Micro CLI provides two gateway modes for accessing your microservices: development (micro run) and production (micro server). Both use the same underlying gateway architecture, ensuring consistent behavior across environments.

Overview

                    ┌─────────────────────┐
                    │   HTTP Requests     │
                    └──────────┬──────────┘
                               │
                    ┌──────────▼──────────┐
                    │   Unified Gateway   │
                    │                     │
                    │  • Service Discovery│
                    │  • HTTP → RPC       │
                    │  • Web Dashboard    │
                    │  • Health Checks    │
                    └──────────┬──────────┘
                               │
                    ┌──────────▼──────────┐
                    │   Your Services     │
                    │  (via Registry)     │
                    └─────────────────────┘

Quick Comparison

Feature micro run micro server
Purpose Local development Production API gateway
Authentication None (public access) JWT tokens required
Process Management Yes (builds & runs services) No (services run separately)
Hot Reload Yes (watches file changes) No
Web UI Login Not required Required (admin/micro default)
Best For Coding, testing, iteration Deployed environments

Development Mode: micro run

Quick Start

# Create and run a service
micro new myservice
cd myservice
micro run

Open http://localhost:8080 - no login required!

What You Get

  • Instant Gateway: HTTP API at /api/{service}/{method}
  • Web Dashboard: Browse and test services at /
  • Hot Reload: Code changes trigger automatic rebuild
  • No Auth: All endpoints are public for easy testing

Example Usage

# Start with hot reload
micro run

# Call a service
curl -X POST http://localhost:8080/api/myservice/Handler.Call \
  -d '{"name": "World"}'

When to Use

  • Writing new services
  • Testing changes locally
  • Debugging service interactions
  • Rapid iteration without deployment

See micro run guide for full details.

Production Mode: micro server

Quick Start

# Start your services separately (e.g., via systemd, docker)
./myservice &

# Start the gateway
micro server --address :8080

Open http://localhost:8080 and log in with admin/micro.

What You Get

  • API Gateway: Secure HTTP endpoint for all services
  • JWT Authentication: Token-based access control
  • Web Dashboard: Service management UI with login
  • User Management: Create users and API tokens
  • Production Ready: Designed for deployed environments

Authentication

All API calls require an Authorization header:

# Get a token (via web UI or login endpoint)
TOKEN="eyJhbGc..."

# Call a service with auth
curl -X POST http://localhost:8080/api/myservice/Handler.Call \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"name": "World"}'

Managing Users & Tokens

  1. Log in: Visit http://localhost:8080 → Enter admin/micro
  2. Create API Token: Go to /auth/tokens → Generate token
  3. Use Token: Copy and use in Authorization: Bearer <token> header

When to Use

  • Production deployments
  • Staging environments
  • Multi-team access (with auth)
  • Public-facing APIs (with security)

Gateway Features (Both Modes)

Both commands provide the same core gateway capabilities:

1. HTTP to RPC Translation

The gateway automatically converts HTTP requests to RPC calls:

POST /api/{service}/{method}
Content-Type: application/json

{"field": "value"}

Becomes an RPC call to:

  • Service: {service}
  • Method: {method}
  • Payload: {"field": "value"}

2. Service Discovery

The gateway queries the registry (mdns, consul, etcd) to find services:

# List all services
curl http://localhost:8080/services

# Returns:
[
  {"name": "myservice", "endpoints": ["Handler.Call", "Handler.List"]},
  {"name": "users", "endpoints": ["Users.Create", "Users.Get"]}
]

Services register automatically when they start - no manual configuration needed!

3. Web Dashboard

Visit / in your browser to:

  • Browse all registered services
  • See available endpoints with request/response schemas
  • Test endpoints with auto-generated forms
  • View service health and status
  • Read API documentation

4. Health Checks

# Aggregate health of all services
curl http://localhost:8080/health

# Kubernetes-style probes
curl http://localhost:8080/health/live   # Is gateway alive?
curl http://localhost:8080/health/ready  # Are services ready?

5. Dynamic Updates

The gateway automatically picks up:

  • New services registering
  • Services going offline
  • Endpoint changes
  • Version updates

No gateway restart needed!

Architecture Benefits

Why Unified?

Previously, micro run and micro server had separate gateway implementations. This caused:

  • Duplicated code (hard to maintain)
  • Feature lag (improvements didn't benefit both)
  • Inconsistent behavior between dev and prod

The unified gateway means:

  • Single codebase for both commands
  • Identical HTTP API in dev and production
  • New features benefit both modes automatically
  • Easier testing and maintenance

What Changed for Users?

Nothing! From a user perspective:

  • micro run works exactly the same (but no auth)
  • micro server works exactly the same (with auth)
  • API endpoints are unchanged
  • Web UI is identical

The unification is internal - your code keeps working.

Common Patterns

Local Development → Production

# 1. Develop locally without auth
micro run
# Test: curl http://localhost:8080/api/...

# 2. Build for production
go build -o myservice

# 3. Deploy services
./myservice &  # or via systemd, docker, k8s

# 4. Start gateway with auth
micro server

# 5. Generate API token (via web UI)
# Use token in production API calls

Multi-Service Development

# micro.mu
service api
    path ./api
    port 8081

service worker
    path ./worker
    port 8082
    depends api

service web
    path ./web
    port 8090
    depends api worker

# Start all with gateway
micro run

See micro run guide for configuration details.

API Gateway Deployment

Deploy micro server as your API gateway in front of all services:

                Internet
                    │
            ┌───────▼────────┐
            │  micro server  │  :8080 (public)
            │   + JWT Auth   │
            └───────┬────────┘
                    │
        ┌───────────┼───────────┐
        │           │           │
    ┌───▼───┐   ┌──▼───┐   ┌──▼────┐
    │ users │   │ posts│   │comments│
    │ :8081 │   │ :8082│   │ :8083  │
    └───────┘   └──────┘   └────────┘
    (internal)  (internal)  (internal)

Only micro server needs public access - services can be internal.

Programmatic Usage

You can also use the gateway in your own Go code:

package main

import (
    "context"
    "log"
    "go-micro.dev/v5/cmd/micro/server"
    "go-micro.dev/v5/store"
)

func main() {
    // Start gateway with custom options
    gw, err := server.StartGateway(server.GatewayOptions{
        Address:     ":9000",
        AuthEnabled: true,  // Enable authentication
        Store:       store.DefaultStore,
        Context:     context.Background(),
    })
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Gateway running on %s", gw.Addr())

    // Block until context is cancelled
    gw.Wait()
}

This gives you full control over gateway configuration in custom deployments.

Troubleshooting

Gateway starts but no services show

Problem: http://localhost:8080 shows empty service list

Solution:

  1. Check services are running: ps aux | grep myservice
  2. Verify registry: services must register via mdns/consul/etcd
  3. Check logs: ~/micro/logs/ for service startup errors

API calls return 404

Problem: curl http://localhost:8080/api/myservice/Handler.Call returns 404

Solution:

  1. Visit http://localhost:8080/services to see registered endpoints
  2. Check exact endpoint name (case-sensitive): Handler.Call vs handler.call
  3. Ensure service is registered: micro services or check web UI

Authentication errors (micro server)

Problem: API returns 401 Unauthorized

Solution:

  1. Generate token: Visit http://localhost:8080/auth/tokens
  2. Use header: Authorization: Bearer <token>
  3. Check token not expired (24h default)
  4. Verify user not deleted (tokens revoked on user deletion)

Port already in use

Problem: micro run or micro server won't start

Solution:

# Check what's using port 8080
lsof -i :8080

# Use different port
micro run --address :9000
micro server --address :9000

Next Steps

Need Help?