go-micro Documentation

A Go agent harness and service framework

23,009 stars Go Go 1 file ยท ~7,630 tokens #ai#ai-agents#distributed-systems#go#golang#mcp#micro#microservices
RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy go-micro on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name go-micro -p 8500:8500 --restart always consul:1.15
Configured Services & Ports
โš™๏ธ consul
image: consul:1.15
๐Ÿ”Œ Ports: 8500:8500
โš™๏ธ app
image: build locally
๐Ÿ”Œ Ports: 9090:9090
โš™๏ธ mcp-gateway
image: build locally
๐Ÿ”Œ Ports: 3001:3001
โš™๏ธ jaeger
image: jaegertracing/all-in-one:1.53
๐Ÿ”Œ Ports: 16686:16686, 4318:4318
docker-compose.yml
yaml (docker-compose.yml)
# Go Micro + MCP Gateway deployment with Docker Compose
#
# This runs:
#   1. Consul     โ€” service registry (discovery)
#   2. App        โ€” your go-micro service(s)
#   3. MCP Gateway โ€” standalone MCP gateway connected to Consul
#   4. Jaeger     โ€” distributed tracing UI
#
# Usage:
#   docker-compose up
#
# Endpoints:
#   MCP Tools:  http://localhost:3001/mcp/tools
#   Consul UI:  http://localhost:8500
#   Jaeger UI:  http://localhost:16686
#   Service:    http://localhost:9090 (RPC)

services:
  # --- Service Registry ---
  consul:
    image: consul:1.15
    ports:
      - "8500:8500"
    command: agent -server -bootstrap-expect=1 -ui -client=0.0.0.0

  # --- Your Go Micro Service ---
  app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "9090:9090"
    environment:
      MICRO_REGISTRY: consul
      MICRO_REGISTRY_ADDRESS: consul:8500
      MICRO_SERVER_ADDRESS: :9090
    depends_on:
      - consul
    restart: unless-stopped

  # --- MCP Gateway (standalone) ---
  mcp-gateway:
    build:
      context: .
      dockerfile: Dockerfile.gateway
    ports:
      - "3001:3001"
    environment:
      MICRO_REGISTRY: consul
      MICRO_REGISTRY_ADDRESS: consul:8500
      MCP_ADDRESS: :3001
      OTEL_EXPORTER_OTLP_ENDPOINT: http://jaeger:4318
    depends_on:
      - consul
      - app
    restart: unless-stopped

  # --- Tracing ---
  jaeger:
    image: jaegertracing/all-in-one:1.53
    ports:
      - "16686:16686"   # UI
      - "4318:4318"     # OTLP HTTP
    environment:
      COLLECTOR_OTLP_ENABLED: "true"

File: README.md

Go Micro [](https://pkg.go.dev/go-micro.dev/v6?tab=doc) [](https://discord.gg/G8Gk5j3uXr)

Go Micro is an agent harness and service framework for Go.

Overview

A harness is the runtime around an agent: the tools it can call, the memory it keeps, the guardrails that bound it, the workflows that trigger it, the services it depends on, and the protocols other agents use to reach it.

Go Micro gives you the harness as Go code. Build an agent and it gets a model, memory, tools, planning, delegation, guardrails, and service discovery; it is reachable over MCP and A2A. Write services and every endpoint becomes an AI-callable tool. Orchestrate the deterministic parts with durable flows. Agents, services, and flows share one runtime because an agent is a distributed system, and building one is building a service.

Sponsors


  

  

Want to support Go Micro and see your logo here? Become a sponsor โ€” reach out on Discord.

Community

Questions, ideas, or just want to build alongside us? Join the Discord.

Commercial Support

Running Go Micro in production, or building on it and want help? Paid support, consulting, training, and retainers are available directly from the maintainer โ€” and they're what keep the project maintained. See Support for the tiers, or open a request.

Contents

Quick Start

Install the CLI:

bash
# Binary (no Go required)
curl -fsSL https://go-micro.dev/install.sh | sh

# Or with Go
go install go-micro.dev/v6/cmd/micro@latest

If install or PATH checks fail, use the install troubleshooting guide before scaffolding your first service.

Fastest start โ€” no API key

Scaffold a service, run it, call it:

bash
micro new helloworld
cd helloworld
micro run

Prefer Docker? The micro image (Docker Hub micro/micro or GitHub Container Registry ghcr.io/micro/go-micro) bundles the CLI and its runtime dependencies:

bash
docker pull micro/micro:latest          # or ghcr.io/micro/go-micro:latest
docker run --rm -it micro/micro new helloworld
docker run --rm -it --network host -v "$(pwd)":/micro/helloworld micro/micro run

Then in another terminal:

bash
curl -X POST http://localhost:8080/api/helloworld/Helloworld.Call \
  -H 'Content-Type: application/json' -d '{"name":"World"}'

This install โ†’ scaffold โ†’ run โ†’ call path is covered by no-secret CI harnesses. To
verify just the local installer and first-run CLI boundaries without network
access or provider keys, use:

bash
make install-smoke

To verify the focused CLI inner-loop contract โ€” scaffold โ†’ run/chat/inspect โ†’ deploy dry-run โ€” use:

bash
make inner-loop

To run only the ordered 0โ†’hero services โ†’ agents โ†’ workflows transcript that CI guards, use:

bash
make zero-to-hero-transcript

To run the broader local contract (including that transcript, chat/inspect CLI boundaries, and deploy dry-run), use:

bash
make harness

First agent on-ramp

After install and the first micro new/micro run smoke check, take the
walkable agent path in this order:

  1. Install troubleshooting โ€” verify the binary installer or go install, PATH, micro --version, and the no-secret smoke path before agent work.

Run make docs-wayfinding to verify the focused no-secret docs/CLI contract that keeps these README and website commands aligned with the installed CLI.

  1. micro agent demo โ€” print the provider-free first-agent demo command and next docs steps from the installed CLI.
  2. micro agent quickcheck (or micro agent debug) โ€” when scaffold โ†’ run โ†’ chat โ†’ inspect stalls, print the short recovery map before you dive into the full debugging guide.
  3. micro examples โ€” print the maintained provider-free runnable examples in copy/paste order.
  4. micro zero-to-hero โ€” print the maintained one-command no-secret lifecycle harness and runnable examples.
  5. Examples wayfinding index โ€” choose the smallest no-secret first-agent, maintained 0โ†’hero support reference, and next interop examples from one map.
  6. Smallest first-agent example โ€” run one service-backed agent with a mock model and no provider key.
  7. No-secret first-agent transcript โ€” run the
    maintained support agent with a mock model and see services โ†’ agents โ†’ workflows succeed without a key.
  8. Your First Agent โ€” build a
    service-backed agent and talk to it with micro chat.
  9. Debugging your agent โ€” use
    micro agent preflight before micro run, micro agent doctor after micro run,
    then micro chat and micro inspect agent <name> to recover run history, memory,
    and provider checks when the first conversation does something unexpected.
  10. 0โ†’hero Reference โ€” complete the
    services โ†’ agents โ†’ workflows loop with scaffold, run, chat, inspect, flow
    history, and deploy dry-run commands that match the maintained harness.

Autonomous improvement loop

Want the same services โ†’ agents โ†’ workflows lifecycle applied to your
repository? micro loop scaffolds the autonomous improvement loop used by Go
Micro itself: a North Star, ranked issue queue, role prompts, GitHub Actions
workflows, and verification for CI-gated PRs.

bash
micro loop init --roles all
micro loop verify

Before turning on the schedule, configure a dispatch token such as
CODEX_TRIGGER_TOKEN, protect the default branch with required CI checks
(go build ./..., go test ./..., and golangci-lint run ./... for this
repository), and seed .github/loop/PRIORITIES.md with one scoped issue per
increment. See the micro loop quickstart
for the setup checklist and operating model.

Generate from a prompt โ€” with an LLM key

Set a provider key, describe what you want, and the AI designs services, writes handlers, compiles, and starts them:

bash
export ANTHROPIC_API_KEY=sk-ant-...   # or OPENAI_API_KEY, GEMINI_API_KEY, ...
micro run --prompt "a task management system with categories" --provider anthropic

The AI designs the architecture, you review it, then it generates handlers with real business logic, compiles them, and starts them:

text
Services:
  โ— task โ€” Task management with status tracking
  โ— project โ€” Project organization

Generate? [Y/n]

Micro
  Services:
    โ— task
    โ— project
  Agents:
    โ—† agent

Then talk to your services from the console:

text
> Create a project called Launch, then add three tasks to it

โ†’ project_Project_Create({"name":"Launch"})
โ† {"record":{"id":"p1..."},"success":true}
โ†’ task_Task_Create({"title":"Design specs","project_id":"p1..."})
โ†’ task_Task_Create({"title":"Write code","project_id":"p1..."})
โ†’ task_Task_Create({"title":"Ship it","project_id":"p1..."})

Created project Launch and added three tasks to it.

When you need a capability that doesn't exist, the agent generates a new service mid-conversation:

text
> I need to track shipping. Create a shipment for order 123 to London.

  โšก generating shipping service...
  โœ“ shipping
  โ†’ shipping_Shipping_Create({"order_id":"123","destination":"London"})
  โ† {"record":{"id":"xyz...","status":"pending"}}

  Created shipment for order 123 going to London.

Edit the generated code by hand at any time โ€” re-running preserves your changes. Read more.

Why an Agent Harness

The first wave of agent frameworks helped developers put a model in a loop. The next problem is operating that loop: connecting it to real tools, scoping what it can touch, preserving state, routing work to specialists, recovering from failures, observing what happened, and letting other agents call it. That is harness work.

Go Micro's answer is to make the harness the same thing you already deploy:

  • Tools are services โ€” endpoint metadata becomes tool schema; RPC executes the call.
  • Agents are services โ€” they register, discover, load-balance, and expose Agent.Chat.
  • Workflows are durable code paths โ€” use flows when the path is known; dispatch to agents when it is not.
  • Safety lives at execution โ€” MaxSteps, LoopLimit, ApproveTool, and tool wrappers run where actions happen.
  • Interop is built in โ€” MCP for tools, A2A for agents, x402 for paid tools.

Use Go Micro when the agent has to operate a system, not just answer a prompt.

Writing Services

Under the hood, a service is a struct with methods. Doc comments and @example tags become tool descriptions for AI agents automatically.

go
package main

import (
    "context"

    "go-micro.dev/v6"
)

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

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

type Say struct{}

// Hello greets a person by name.
// @example {"name": "Alice"}
func (h *Say) Hello(ctx context.Context, req *Request, rsp *Response) error {
    rsp.Message = "Hello " + req.Name
    return nil
}

func main() {
    service := micro.NewService("greeter")
    service.Handle(new(Say))
    service.Run()
}

Run it and everything is accessible โ€” REST, gRPC, MCP, agent playground:

bash
micro run
# Dashboard:   http://localhost:8080
# API:         http://localhost:8080/api/{service}/{method}
# Agent:       http://localhost:8080/agent
# MCP Tools:   http://localhost:8080/mcp/tools

You can also scaffold a service from a template:

bash
micro new helloworld
micro new contacts --template crud

Building Agents

An Agent is a service with an LLM inside it. It has a proto-defined Agent.Chat RPC endpoint, registers in the registry, and is callable like any service:

go
agent := micro.NewAgent("task-mgr",
    micro.AgentServices("task", "project"),
    micro.AgentPrompt("You manage tasks and projects. You understand deadlines and priorities."),
    micro.AgentProvider("anthropic"),
)
agent.Run()

The agent discovers its services from the registry, scopes its tools to their endpoints, and maintains conversation memory in the store. It registers itself so micro chat and other agents can find it.

go
// Programmatic interaction
resp, _ := agent.Ask(ctx, "What tasks are overdue?")
fmt.Println(resp.Reply)

Multiple agents coordinate via RPC โ€” each is a service with an Agent.Chat endpoint. micro chat routes to the right one.

bash
micro agent list                    # list registered agents
micro call task-mgr Agent.Chat '{"message": "What tasks are overdue?"}'

Plan & Delegate

Every agent gets two built-in harness capabilities, exposed as tools โ€” no extra setup or separate graph runtime:

  • plan โ€” for multi-step work, the agent records an ordered plan in its store-backed memory and stays oriented across turns.
  • delegate โ€” the agent hands a self-contained subtask to another agent. If a registered agent already owns the relevant services, the hand-off goes over RPC to that agent; otherwise a focused, short-lived sub-agent is created for the subtask with its own isolated context.

This keeps intelligence distributed: an agent doesn't need to know how to do everything, only who does. See examples/agent-plan-delegate.

go
// A sub-agent is just an agent โ€” created with New, talked to with Ask.
// delegate-first: reuse a registered agent, or spin up a focused one.
resp, _ := agent.Ask(ctx, "Plan the launch, create the tasks, and have comms notify the owner.")

Batteries included, pluggable

Just as a service composes pluggable abstractions (registry, broker, store), an agent composes a model, memory, and tools โ€” sane defaults out of the box, each swappable.

go
agent := micro.NewAgent("assistant",
    micro.AgentProvider("anthropic"),                 // model โ€” swap the provider
    micro.AgentCompactMemory(40, 12),                 // memory โ€” durable, summarized, recallable
    micro.AgentTool("weather", "Get the weather for a city",
        map[string]any{"city": map[string]any{"type": "string"}},
        func(ctx context.Context, in map[string]any) (string, error) {
            return getWeather(in["city"].(string))    // tools beyond your services โ€” any function
        }),
    micro.AgentMaxSteps(8),                            // guardrails
)

Memory is durable and store-backed by default (Postgres, NATS KV, or file), so an agent picks up where it left off after a restart โ€” or supply your own with AgentMemory. Long-running agents can opt into AgentCompactMemory(maxMessages, keepRecent): older turns are collapsed into a deterministic summary, recent turns stay verbatim, and relevant archived turns are recalled on future asks without replaying the whole conversation. Tools are your services automatically, plus any function you register with AgentTool.

Every endpoint is an AI-callable tool โ€” and it can be a paid tool. Go Micro supports x402, the HTTP 402 payment standard for agents, so a tool can require a stablecoin payment and an agent can settle it autonomously. It's opt-in and carries no crypto in the framework: verification is delegated to a pluggable facilitator (Coinbase, Alchemy, self-hosted), so Base and Solana are just different facilitators.

bash
# Charge for tool calls at the MCP gateway (off unless you set a pay-to address)
micro mcp serve --x402_pay_to 0xYourAddress --x402_network solana --x402_amount 10000
# Per-tool amounts via a config file
micro mcp serve --x402_config x402.json

See the Payments (x402) guide.

Reachable by other agents (A2A)

Within a Go Micro system, agents reach each other over RPC. To make them reachable by agents on other frameworks, Go Micro speaks the Agent2Agent (A2A) protocol. The A2A gateway discovers your agents from the registry, generates an Agent Card for each from its metadata โ€” the same way the MCP gateway derives tools from service endpoints โ€” and translates incoming A2A tasks to the agent's Agent.Chat RPC. No per-agent code: register an agent and it's reachable over A2A.

bash
micro a2a serve --address :4000    # gateway: expose every registered agent over A2A
micro a2a list                     # agents and their Agent Card URLs

Or skip the gateway entirely โ€” an agent can serve its own A2A endpoint directly, handling tasks in-process:

go
micro.NewAgent("task-mgr", micro.AgentServices("task"), micro.AgentA2A(":4000"))

It works both ways. To call an agent on another framework, an a2a.Client is wired into the two places that hand off work: flow.A2A(url) as a workflow step (the cross-framework Dispatch), and delegate to an http(s) URL from inside an agent.

MCP exposes your services as tools; A2A exposes your agents as agents. See the A2A guide.

Features

AI

Feature Details
Agents micro.NewAgent() โ€” intelligent layer that manages services
Plan & delegate Built-in agent tools โ€” plan multi-step work, delegate subtasks to other agents
Pluggable memory Durable store-backed conversation memory by default; swap with AgentMemory
Custom tools AgentTool โ€” give an agent any function as a tool, beyond its services
Guardrails MaxSteps (stop on count), LoopLimit (stop repeated no-progress calls), ApproveTool (human-in-the-loop)
Tool middleware AgentWrapTool โ€” wrap tool execution for logging, metrics, or retries (like client/server wrappers)
Workflows micro.NewFlow() โ€” event-driven; one step, ordered durable steps, or triggers an agent
Durable execution Checkpointed flow steps survive a crash and resume where they stopped; store-backed by default, pluggable backend
MCP gateway Every endpoint is an AI tool automatically
A2A gateway Every agent is reachable over the Agent2Agent protocol; cards generated from the registry (micro a2a)
Payments (x402) Opt-in per-call payments for tools via the x402 standard; pluggable facilitator (Base, Solana, โ€ฆ)
9 LLM providers Anthropic, OpenAI, Gemini, Groq, Mistral, Together, Atlas Cloud, MiniMax, Ollama (local + cloud)
Interactive console micro run includes a chat console for talking to services
Service generation micro run --prompt โ€” describe a system, get running services

Framework

Feature Details
Service registry mDNS (default), Consul, etcd
RPC client/server gRPC transport, load balancing, streaming
Pub/sub events NATS, RabbitMQ, HTTP broker
Key-value store File (bbolt), Postgres, NATS KV
Typed model layer CRUD + queries, SQLite/Postgres backends
Everything swappable All abstractions are Go interfaces

Developer experience & deployment

Feature Details
Hot reload micro run watches files, rebuilds on change
Templates micro new --template crud/pubsub/api
One-command deploy micro deploy user@server โ€” SSH + systemd, no Docker

CLI

Command Purpose
micro run --prompt "..." Generate services + agent, start with interactive console
micro run Dev mode: hot reload, gateway, interactive console
micro run -d Detached mode (no console)
micro chat Standalone chat (when not using micro run)
micro agent list List registered agents
micro new myservice Scaffold a service
micro call service endpoint '{}' Call a service or agent from the CLI
micro build Compile production binaries
micro deploy user@server Deploy via SSH + systemd

Multi-Service Projects

Run multiple services together:

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

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

g := micro.NewGroup(users, orders)
g.Run()

Or use a micro.mu config file:

text
service users
    path ./users

service orders
    path ./orders
    depends users

Data Model

Typed persistence with CRUD and queries:

go
type User struct {
    ID    string `json:"id" model:"key"`
    Name  string `json:"name"`
    Email string `json:"email" model:"index"`
}

db := service.Model()
db.Register(&User{})
db.Create(ctx, &User{ID: "1", Name: "Alice", Email: "[email protected]"})

var results []*User
db.List(ctx, &results, model.Where("email", "[email protected]"))

Backends: memory (default), SQLite, Postgres.

AI Providers

Swap providers with a single import โ€” same interface everywhere:

Provider Default Model
Anthropic claude-sonnet-4-20250514
OpenAI gpt-4o
Google Gemini gemini-2.5-flash
Groq llama-3.3-70b-versatile
Mistral mistral-large-latest
Together AI meta-llama/Llama-3.3-70B-Instruct-Turbo
Atlas Cloud deepseek-ai/DeepSeek-V3-0324
MiniMax MiniMax-M3
Ollama llama3.2 (local)
go
m := ai.New("anthropic", ai.WithAPIKey(key))
resp, _ := m.Generate(ctx, &ai.Request{Prompt: "hello"})

Examples

New to agents? Follow the first-agent on-ramp, then use the examples index for the full services โ†’ agents โ†’ workflows map.

  • hello-world โ€” Basic RPC service
  • multi-service โ€” Multiple services in one binary
  • mcp โ€” MCP integration with AI agents
  • first-agent โ€” Smallest provider-free service-backed agent
  • agent-plan-delegate โ€” Agent planning and multi-agent delegation
  • agent-durable โ€” Checkpoint and resume an agent run without replaying completed tool side effects
  • grpc-interop โ€” Call go-micro from any gRPC client

See all examples.

Docs

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


File: config/source/cli/README.md

cli Source

The cli source reads config from parsed flags via a cli.Context.

Format

We expect the use of the urfave/cli package. Upper case flags will be lower cased. Dashes will be used as delimiters for nesting.

Example

go
micro.Flags(
    cli.StringFlag{
        Name: "database-address",
        Value: "127.0.0.1",
        Usage: "the db address",
    },
    cli.IntFlag{
        Name: "database-port",
        Value: 3306,
        Usage: "the db port",
    },
)

Becomes

json
{
  "database": {
    "address": "127.0.0.1",
    "port": 3306
  }
}

New and Load Source

Because a cli.Context is needed to retrieve the flags and their values, it is recommended to build your source from within a cli.Action.

go
func main() {
    // New Service
    service := micro.NewService(
        micro.Name("example"),
        micro.Flags(
            cli.StringFlag{
                Name: "database-address",
                Value: "127.0.0.1",
                Usage: "the db address",
            },
        ),
    )

    var clisrc source.Source

    service.Init(
        micro.Action(func(c *cli.Context) {
            clisrc = cli.NewSource(
                cli.Context(c),
	    )
            // Alternatively, just setup your config right here
        }),
    )

    // ... Load and use that source ...
    conf := config.NewConfig()
    conf.Load(clisrc)
}

File: config/source/env/README.md

Env Source

The env source reads config from environment variables

Format

We expect environment variables to be in the standard format of FOO=bar

Keys are converted to lowercase and split on underscore.

Format example

bash
DATABASE_ADDRESS=127.0.0.1
DATABASE_PORT=3306

Becomes

json
{
  "database": {
    "address": "127.0.0.1",
    "port": 3306
  }
}

Prefixes

Environment variables can be namespaced so we only have access to a subset. Two options are available:

go
WithPrefix(p ...string)
WithStrippedPrefix(p ...string)

The former will preserve the prefix and make it a top level key in the config. The latter eliminates the prefix, reducing the nesting by one.

Prefixes example

Given ENVs of:

bash
APP_DATABASE_ADDRESS=127.0.0.1
APP_DATABASE_PORT=3306
VAULT_ADDR=vault:1337

and a source initialized as follows:

go
src := env.NewSource(
    env.WithPrefix("VAULT"),
    env.WithStrippedPrefix("APP"),
)

The resulting config will be:

json
{
  "database": {
    "address": "127.0.0.1",
    "port": 3306
  },
  "vault": {
    "addr": "vault:1337"
  }
}

New Source

Specify source with data

go
src := env.NewSource(
  // optionally specify prefix
  env.WithPrefix("MICRO"),
)

Load Source

Load the source into config

go
// Create new config
conf := config.NewConfig()

// Load env source
conf.Load(src)

File: config/source/file/README.md

File Source

The file source reads config from a file.

It uses the File extension to determine the Format e.g config.yaml has the yaml format.
It does not make use of encoders or interpet the file data. If a file extension is not present
the source Format will default to the Encoder in options.

Example

A config file format in json

json
{
  "hosts": {
    "database": {
      "address": "10.0.0.1",
      "port": 3306
    },
    "cache": {
      "address": "10.0.0.2",
      "port": 6379
    }
  }
}

New Source

Specify file source with path to file. Path is optional and will default to config.json

go
fileSource := file.NewSource(
	file.WithPath("/tmp/config.json"),
)

File Format

To load different file formats e.g yaml, toml, xml simply specify them with their extension

go
fileSource := file.NewSource(
        file.WithPath("/tmp/config.yaml"),
)

If you want to specify a file without extension, ensure you set the encoder to the same format

go
e := toml.NewEncoder()

fileSource := file.NewSource(
        file.WithPath("/tmp/config"),
        source.WithEncoder(e),
)

Load Source

Load the source into config

go
// Create new config
conf := config.NewConfig()

// Load file source
conf.Load(fileSource)

File: config/source/flag/README.md

Flag Source

The flag source reads config from flags

Format

We expect the use of the flag package. Upper case flags will be lower cased. Dashes will be used as delimiters.

Example

go
dbAddress := flag.String("database_address", "127.0.0.1", "the db address")
dbPort := flag.Int("database_port", 3306, "the db port)

Becomes

json
{
  "database": {
    "address": "127.0.0.1",
    "port": 3306
  }
}

New Source

go
flagSource := flag.NewSource(
	// optionally enable reading of unset flags and their default
	// values into config, defaults to false
	IncludeUnset(true)
)

Load Source

Load the source into config

go
// Create new config
conf := config.NewConfig()

// Load flag source
conf.Load(flagSource)

File: config/source/memory/README.md

Memory Source

The memory source provides in-memory data as a source

Memory Format

The expected data format is json

json
data := []byte(`{
    "hosts": {
        "database": {
            "address": "10.0.0.1",
            "port": 3306
        },
        "cache": {
            "address": "10.0.0.2",
            "port": 6379
        }
    }
}`)

New Source

Specify source with data

go
memorySource := memory.NewSource(
	memory.WithJSON(data),
)

Load Source

Load the source into config

go
// Create new config
conf := config.NewConfig()

// Load memory source
conf.Load(memorySource)

File: config/source/nats/README.md

Nats Source

The nats source reads config from nats key/values

Nats Format

The nats source expects keys under the default bucket default default key micro_config

Values are expected to be json

text
nats kv put default micro_config '{"nats": {"address": "10.0.0.1", "port": 8488}}'
text
conf.Get("nats")

New Source

Specify source with data

go
natsSource := nats.NewSource(
	nats.WithUrl("127.0.0.1:4222"),
	nats.WithBucket("my_bucket"),
	nats.WithKey("my_key"),
)

Load Source

Load the source into config

go
// Create new config
conf := config.NewConfig()

// Load nats source
conf.Load(natsSource)

Watch

go
wh, _ := natsSource.Watch()

for {
	v, err := watcher.Next()
	if err != nil {
		log.Fatalf("err %v", err)
	}

	log.Infof("data %v", string(v.Data))
}

File: config/README.md

Config [](https://godoc.org/github.com/micro/go-micro/config)

Config is a pluggable dynamic config package

Most config in applications are statically configured or include complex logic to load from multiple sources.
Go Config makes this easy, pluggable and mergeable. You'll never have to deal with config in the same way again.

Features

  • Dynamic Loading - Load configuration from multiple source as and when needed. Go Config manages watching config sources
    in the background and automatically merges and updates an in memory view.

  • Pluggable Sources - Choose from any number of sources to load and merge config. The backend source is abstracted away into
    a standard format consumed internally and decoded via encoders. Sources can be env vars, flags, file, etcd, k8s configmap, etc.

  • Mergeable Config - If you specify multiple sources of config, regardless of format, they will be merged and presented in
    a single view. This massively simplifies priority order loading and changes based on environment.

  • Observe Changes - Optionally watch the config for changes to specific values. Hot reload your app using Go Config's watcher.
    You don't have to handle ad-hoc hup reloading or whatever else, just keep reading the config and watch for changes if you need
    to be notified.

  • Sane Defaults - In case config loads badly or is completely wiped away for some unknown reason, you can specify fallback
    values when accessing any config values directly. This ensures you'll always be reading some sane default in the event of a problem.