项目文件夹

文件
Asim Aslam c7657f73f4
goreleaser / goreleaser (push) Has been cancelled
Refactor agent plan storage, update docs, and release v6 (#2977)
* test(harness): read agent plan from the scoped store

The store-scoping change moved an agent's plan from the default table
key agent/{name}/plan to its own table (database "agent", table {name},
key "plan"). The plan-delegate harness tests still read the old key and
failed with 'not found'; read through store.Scope(mem, "agent", name)
like the agent does.

* docs: orient agents-first across README, landing, and docs overview

Lead with agents (then services and flows), surface MCP + A2A as the
interop story, and frame agents as services. Landing hero and feature
grid reordered agents-first with an A2A gateway card.

* v6: module path go-micro.dev/v6, TLS secure by default, NewService

Cut v6. Three breaking changes, bundled so the major bump is paid once:

- Module path go-micro.dev/v5 -> go-micro.dev/v6 across all imports + go.mod.
- TLS verification on by default (was off). MICRO_TLS_SECURE removed;
  MICRO_TLS_INSECURE=true opts out for self-signed/dev.
- micro.NewService(name, opts...) is the canonical service constructor,
  symmetric with NewAgent/NewFlow; micro.New kept as a deprecated alias;
  the old name-less NewService(opts...) removed. Generators emit NewService.

Also ports the JWT auth token provider in-module (go-micro.dev/v6/auth/jwt/token
on golang-jwt/jwt/v5), dropping the v5-pinned github.com/micro/plugins/v5/auth/jwt
and the deprecated dgrijalva/jwt-go.

Docs/README/landing updated to v6 and @latest; v5->v6 migration guide added;
CHANGELOG cut as [6.0.0]. Blog posts left at their historical versions.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-18 11:55:35 +01:00
..

API Gateway

The gateway/api package provides HTTP API gateway functionality for go-micro services. It translates HTTP requests into RPC calls and serves a web dashboard for browsing and calling services.

Features

  • HTTP to RPC translation - Call microservices via HTTP
  • Web dashboard - Browse and test services in the browser
  • Authentication - Optional JWT-based auth
  • MCP integration - Expose services to AI agents
  • Flexible configuration - Use in dev or production
  • Service discovery - Auto-detect services from registry

Usage

Basic Gateway

package main

import (
    "context"
    "net/http"

    "go-micro.dev/v5/gateway/api"
)

func main() {
    // Create gateway with custom handler
    gw, err := api.New(api.Options{
        Address: ":8080",
        Context: context.Background(),
        HandlerRegistrar: func(mux *http.ServeMux) error {
            // Register your HTTP handlers
            mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
                w.Write([]byte("Hello from gateway"))
            })
            return nil
        },
    })
    if err != nil {
        panic(err)
    }

    // Block until shutdown
    gw.Wait()
}

Gateway with MCP

gw, err := api.New(api.Options{
    Address:    ":8080",
    MCPEnabled: true,
    MCPAddress: ":3000", // MCP on separate port
    HandlerRegistrar: registerHandlers,
})

Gateway with Authentication

gw, err := api.New(api.Options{
    Address:     ":8080",
    AuthEnabled: true, // Handler registrar should add auth middleware
    HandlerRegistrar: func(mux *http.ServeMux) error {
        // Register handlers with auth middleware
        return registerAuthenticatedHandlers(mux)
    },
})

Blocking Mode

// Run blocks until shutdown
err := api.Run(api.Options{
    Address: ":8080",
    HandlerRegistrar: registerHandlers,
})

Options

type Options struct {
    // Address to listen on (default: ":8080")
    Address string

    // AuthEnabled signals that authentication is required
    // The HandlerRegistrar should implement auth checks
    AuthEnabled bool

    // Context for cancellation (default: context.Background())
    Context context.Context

    // Logger for gateway messages (default: log.Default())
    Logger *log.Logger

    // HandlerRegistrar registers HTTP handlers on the mux
    HandlerRegistrar func(mux *http.ServeMux) error

    // MCPEnabled enables the MCP gateway
    MCPEnabled bool

    // MCPAddress is the address for MCP gateway (e.g., ":3000")
    MCPAddress string

    // Registry for service discovery (default: registry.DefaultRegistry)
    Registry registry.Registry
}

Architecture

┌─────────────────────────────────────────┐
│         gateway/api Package              │
│  ┌────────────────────────────────────┐ │
│  │  Gateway                           │ │
│  │  - Manages HTTP server             │ │
│  │  - Calls HandlerRegistrar          │ │
│  │  - Starts MCP if enabled           │ │
│  └────────────────────────────────────┘ │
└─────────────────────────────────────────┘
               ↓ delegates to
┌─────────────────────────────────────────┐
│     HandlerRegistrar (user-provided)     │
│  ┌────────────────────────────────────┐ │
│  │  func(mux *http.ServeMux) error    │ │
│  │  - Registers routes                │ │
│  │  - Adds middleware (auth, etc.)    │ │
│  │  - Sets up templates               │ │
│  └────────────────────────────────────┘ │
└─────────────────────────────────────────┘
               ↓ uses
┌─────────────────────────────────────────┐
│         Microservices (via RPC)          │
└─────────────────────────────────────────┘

Integration

In micro run (Development)

// cmd/micro/run/run.go
import "go-micro.dev/v5/gateway/api"

gw, err := api.New(api.Options{
    Address:     ":8080",
    AuthEnabled: false, // No auth in dev mode
    HandlerRegistrar: func(mux *http.ServeMux) error {
        // Register dev-mode handlers (no auth)
        mux.HandleFunc("/", dashboardHandler)
        mux.HandleFunc("/api/", apiHandler)
        return nil
    },
})

In micro server (Production)

// cmd/micro/server/server.go
import "go-micro.dev/v5/gateway/api"

gw, err := api.New(api.Options{
    Address:     ":8080",
    AuthEnabled: true, // Auth required in production
    HandlerRegistrar: func(mux *http.ServeMux) error {
        // Register prod handlers with auth middleware
        mux.HandleFunc("/", authMiddleware(dashboardHandler))
        mux.HandleFunc("/api/", authMiddleware(apiHandler))
        return nil
    },
})

Custom Application

// Your app
import "go-micro.dev/v5/gateway/api"

func main() {
    gw, err := api.New(api.Options{
        Address: ":8080",
        HandlerRegistrar: func(mux *http.ServeMux) error {
            // Your custom handlers
            mux.HandleFunc("/health", healthHandler)
            mux.HandleFunc("/metrics", metricsHandler)
            mux.HandleFunc("/api/", proxyToServices)
            return nil
        },
    })

    if err != nil {
        log.Fatal(err)
    }

    log.Println("Gateway running on :8080")
    gw.Wait()
}

Comparison with Old Architecture

Before (Duplicated Code)

cmd/micro/run/gateway/
  └── gateway.go (300+ lines)

cmd/micro/server/
  └── gateway.go (150+ lines)

❌ Code duplication
❌ Inconsistent behavior
❌ Hard to reuse

After (Unified)

gateway/api/
  └── gateway.go (150 lines, reusable)

cmd/micro/server/
  └── gateway.go (70 lines, compatibility wrapper)

cmd/micro/run/
  └── Uses api.New() directly

✅ Single source of truth
✅ Consistent behavior
✅ Easy to reuse in custom apps

Benefits

  1. Reusability - Use in any Go application, not just micro CLI
  2. Testability - Easy to test with custom handler registrars
  3. Flexibility - Supports different configurations (dev, prod, custom)
  4. Consistency - Same gateway code for all use cases
  5. Maintainability - One place to fix bugs and add features

Migration Guide

From cmd/micro/server/gateway.go

Before:

import "go-micro.dev/v5/cmd/micro/server"

gw, err := server.StartGateway(server.GatewayOptions{
    Address: ":8080",
    AuthEnabled: true,
    Store: myStore,
})

After:

import "go-micro.dev/v5/gateway/api"

gw, err := api.New(api.Options{
    Address: ":8080",
    AuthEnabled: true,
    HandlerRegistrar: func(mux *http.ServeMux) error {
        // Register your handlers
        // Pass store as closure
        return registerHandlers(mux, myStore)
    },
})

Examples

See:

  • cmd/micro/server/gateway.go - Production gateway with auth
  • cmd/micro/run/run.go - Development gateway without auth
  • examples/gateway/ - Custom gateway examples (coming soon)

License

Apache 2.0