Help us shape the future of Go! Take the 2026 Go Developer Survey

micro

package module
v0.0.0-...-a11fdd8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

README

Go Micro Go.Dev reference

Go Micro is a pluggable framework for building microservices in Go.

You write services; the framework gives them service discovery, RPC, and pub/sub out of the box. Every moving part — how services find each other, how they talk, how messages are encoded, where state is stored — is a Go interface with a default implementation you can swap without touching business code.

Contents

Core Concepts

Service — the unit of work

A Service is the top-level handle you build everything around. It wires together the pluggable pieces below, registers itself for discovery, and manages its own lifecycle (Init → Run → graceful stop on signal/context).

service := micro.New("greeter")   // create
service.Handle(new(Say))          // register RPC handlers
service.Run()                     // start, block until signalled, then stop

Each service owns its own client, server, store, and cache, so several services can run in one binary (see Multi-Service Projects).

The pluggable abstractions

Everything the framework does is expressed as an interface with a default implementation and a functional-options constructor. Pick a different backend by passing a different option — no business-code changes.

Abstraction Responsibility Default Other backends
Registry Service discovery — register/lookup service nodes mDNS Consul, etcd, NATS, Nacos
Broker Asynchronous pub/sub messaging HTTP NATS, RabbitMQ, Kafka, memory
Transport Point-to-point synchronous communication (the RPC pipe) HTTP gRPC, NATS
Client Makes RPC calls (retries, timeouts, streaming) RPC gRPC
Server Serves RPC handlers and subscribers RPC gRPC
Selector Picks one node from Registry results (load balancing) round-robin —
Codec Encodes/decodes messages protobuf/JSON grpc, bytes, jsonrpc, text
Store Key-value persistence file (bbolt) Postgres, MySQL, NATS JetStream KV, Redis (Dragonfly, Valkey), MongoDB
Config Dynamic configuration from sources — env, file, flag, CLI, NATS, Nacos, etcd, Consul, memory
Model Typed data layer (CRUD + queries) memory SQLite, Postgres, MongoDB
Sync Distributed locks and leader election memory etcd, Redis (Dragonfly, Valkey)
Cache Key-value cache memory Redis
Logger Structured logging built-in (slog-style) slog, Zap, zerolog

Each abstraction has a README in its package directory (registry/, broker/, wrapper/, …) covering the concept, semantics and available backends.

Supporting pieces: Auth (accounts/JWT), Events (JetStream streams), Metadata (request context), Wrapper (client/server middleware), Logger, and Debug (profile/trace/health).

How a request flows

An RPC call travels through the abstractions in order:

Client.Call
  → Selector picks a node from the Registry
  → Transport opens a connection and sends the Message
  → Server receives it
  → Codec decodes the body
  → Wrapper middleware chain runs
  → your Handler executes
  → Codec encodes the reply back

Because each hop is an interface, you can change the wire protocol (HTTP → gRPC → NATS), the discovery backend, or add middleware without rewriting handlers.

Message & headers

The unit that moves across any Transport is a Message:

type Message struct {
    Header map[string]string // metadata
    Body   []byte            // payload
}

The header keys are standardized in the transport/headers package (Micro-Service, Micro-Endpoint, Micro-Topic, Micro-Error, Micro-Trace-ID, …). Every transport (HTTP, gRPC, NATS) and the broker/server use the same key names, so client, server, and middleware read request metadata the same way regardless of the underlying wire protocol. transport/headers is not a transport backend — it's the shared vocabulary the backends fill in.

Functional options

Configuration everywhere uses the functional-options pattern: Option func(*Options). Options hold pointers to the pluggable pieces so they can be swapped at runtime, and setting a top-level option (e.g. Registry) cascades down to the client, server, and broker so the components stay consistent.

service := micro.New("greeter",
    micro.Address(":8080"),
    micro.Registry(consul.NewConsulRegistry()),   // swaps discovery for the whole service
)

Quick Start

Requires Go 1.26 or later. Every module in this repository (core, plugins, gateways, examples) declares go 1.26.0, so any combination of them builds with the same toolchain.

Install the CLI:

go install github.com/flylib/go-micro/cmd/micro@main

Scaffold a service, run it, call it:

micro new helloworld
cd helloworld
micro run

In another terminal, call it with the CLI:

micro call helloworld Helloworld.Call '{"name":"World"}'

Or over HTTP, through the gateway that micro run starts on :8080. Auth is on, so log in first with the default admin / micro:

curl -c /tmp/micro.jar -d 'id=admin&password=micro' http://localhost:8080/auth/login
curl -b /tmp/micro.jar -X POST http://localhost:8080/api/helloworld/Helloworld/Call \
  -H 'Content-Type: application/json' -d '{"name":"World"}'

micro run gives you:

# Dashboard:  http://localhost:8080
# API:        http://localhost:8080/api/{service}/{method}
# Health:     http://localhost:8080/health

Writing a Service

A service is a struct with methods. Each exported method with the (ctx, *Request, *Response) error shape becomes an RPC endpoint.

package main

import (
    "context"

    "github.com/flylib/go-micro"
)

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

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

type Say struct{}

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

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

Scaffold from a template instead:

micro new helloworld               # default template
micro new contacts --template crud # crud / pubsub / api

Multi-Service Projects

Run several services in one binary with a shared lifecycle:

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

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

g := micro.NewGroup(users, orders)
g.Run() // all start together, all stop together on signal

Or describe a multi-service project with a micro.mu file (services start in dependency order):

service users
    path ./users

service orders
    path ./orders
    depends users

Pluggable Backends

Swap any abstraction by importing a backend and passing it as an option — the rest of your code is unchanged.

import (
    "github.com/flylib/go-micro"
    "github.com/flylib/go-micro/registry/consul"
    "github.com/flylib/go-micro/transport/grpc"
    "github.com/flylib/go-micro/broker/nats"
)

service := micro.New("orders",
    micro.Registry(consul.NewConsulRegistry()),
    micro.Transport(grpc.NewTransport()),
    micro.Broker(nats.NewNatsBroker()),
)
  • Registry: mDNS (default), Consul, etcd, NATS, Nacos
  • Broker: HTTP (default), NATS, RabbitMQ, Kafka, memory
  • Transport: HTTP (default), gRPC, NATS
  • Store: file/bbolt (default), Postgres, MySQL, NATS JetStream KV, Redis / Dragonfly / Valkey, MongoDB
  • Sync (locks, leader election): memory (default), etcd, Redis / Dragonfly / Valkey
  • Model: memory (default), SQLite, Postgres, MongoDB
  • Config sources: env, file, flag, CLI, memory, NATS, Nacos, etcd, Consul
  • Logger: built-in (default), slog, Zap, zerolog

Data Model

Typed persistence with CRUD and queries on top of the store:

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: "alice@example.com"})

var results []*User
db.List(ctx, &results, model.Where("email", "alice@example.com"))

Backends: memory (default), SQLite, Postgres, MongoDB. See model/.

Edge Gateways

gateway/ holds two edge gateways for traffic from outside the cluster: a Go gateway and an OpenResty one. They follow one contract and pass one conformance suite. Both discover services in etcd, Consul or Nacos, take hot-reloaded rules from a file, etcd, Consul or Nacos, and offer routing, load balancing, retries, IP restriction, JWT auth and rate limiting.

  • gRPC in, forwarded to services as opaque frames: no .proto files at the gateway.
  • HTTP/JSON for browsers and mini programs.
    • POST /api/<service>/<Handler>/<Method>, or REST endpoints transcoded from google.api.http annotations. protoc-gen-micro-gateway generates the rules.
    • JWT claims such as the user id are forwarded to services as metadata.
  • WebSocket /ws: calls, streams, topic subscriptions, and pushes from services with gateway/push.

Services only need the gRPC server (server/grpc) and a proto package equal to their registry name.

Using the Modules

The core is github.com/flylib/go-micro. Every backend is its own module (registry/nacos, store/redis, gateway/proxy, …), so you only download the SDKs you use.

go get github.com/flylib/go-micro@main
go get github.com/flylib/go-micro/registry/nacos@main github.com/flylib/go-micro/server/grpc@main
  • No release tags. @main resolves to a pseudo-version of the latest commit (v0.0.0-<time>-<hash>). The in-repo modules require each other at one pushed commit, so any mix of them resolves to a consistent set. Pin a commit with @<hash>.
  • Go 1.26 or later for every module.
  • Commands. The CLI tools in the core module install with go install …@main: cmd/micro, cmd/protoc-gen-micro, cmd/protoc-gen-micro-gateway.
  • Binaries in plugin modules. The Go gateway's micro-gateway lives in a plugin module, and go install …@version refuses those modules. Each one keeps replace directives pointing into this repository, so it builds inside the repository without go.work. Build such binaries from a checkout (cd gateway/proxy && go build ./cmd/micro-gateway). Importing these modules as libraries is unaffected.

CLI

Command Purpose
micro new myservice Scaffold a service (--template crud/pubsub/api)
micro run Dev mode: hot reload + HTTP API gateway + dashboard
micro server Production mode: gateway with auth + dashboard
micro call service Endpoint '{}' Call a service from the CLI
micro services List registered services
micro describe service Show a service's endpoints
micro gen proto Generate code from .proto (needs protoc + protoc-gen-micro)
micro build Compile production binaries
micro deploy user@server Deploy via SSH + systemd

Examples

See all examples.

Package reference: https://pkg.go.dev/github.com/flylib/go-micro

Development

The repo is a multi-module workspace (core + one module per pluggable backend + examples), wired together by go.work — open the repo root in your IDE and every module resolves against local sources, no replace juggling needed while developing or debugging.

go build ./...                    # build the core (workspace mode)
cd examples/smoke && go test .    # end-to-end smoke tests
GOWORK=off go build ./...         # build a module standalone (as consumers see it)

Each plugin module also carries its own replace github.com/flylib/go-micro => ../.. so it still builds standalone outside the workspace.

Go version. All modules and go.work declare the same go 1.26.0. The floor is set by dependencies, not taste: etcd client v3.7 needs Go 1.26, and golang.org/x/time and golang.org/x/text need 1.25. Keep it in step when adding a module or raising the version (go-version-file: go.mod in CI follows the root module):

for f in $(git ls-files '*go.mod'); do (cd "$(dirname "$f")" && go mod edit -go=1.26.0); done
go work edit -go=1.26.0

Documentation

Overview

Package micro is a pluggable framework for microservices

Index

Constants

This section is empty.

Variables

View Source
var Action = service.Action
View Source
var AddListenOption = service.AddListenOption
View Source
var Address = service.Address
View Source
var AfterStart = service.AfterStart
View Source
var AfterStop = service.AfterStop
View Source
var Auth = service.Auth
View Source
var BeforeStart = service.BeforeStart
View Source
var BeforeStop = service.BeforeStop
View Source
var Broker = service.Broker
View Source
var Cache = service.Cache
View Source
var Client = service.Client
View Source
var Cmd = service.Cmd
View Source
var Config = service.Config
View Source
var Context = service.Context
View Source
var Flags = service.Flags
View Source
var Handle = service.Handle
View Source
var HandleSignal = service.HandleSignal
View Source
var Logger = service.Logger
View Source
var Metadata = service.Metadata
View Source
var Model = service.Model
View Source
var Name = service.Name
View Source
var Profile = service.Profile
View Source
var RegisterInterval = service.RegisterInterval
View Source
var RegisterTTL = service.RegisterTTL
View Source
var Registry = service.Registry
View Source
var Selector = service.Selector
View Source
var Server = service.Server
View Source
var Store = service.Store
View Source
var Tracer = service.Tracer
View Source
var Transport = service.Transport
View Source
var Version = service.Version
View Source
var WrapCall = service.WrapCall
View Source
var WrapClient = service.WrapClient
View Source
var WrapHandler = service.WrapHandler
View Source
var WrapSubscriber = service.WrapSubscriber

Functions

func NewContext

func NewContext(ctx context.Context, s Service) context.Context

NewContext returns a new Context with the Service embedded within it.

func RegisterHandler

func RegisterHandler(s server.Server, h interface{}, opts ...server.HandlerOption) error

RegisterHandler is syntactic sugar for registering a handler.

func RegisterSubscriber

func RegisterSubscriber(topic string, s server.Server, h interface{}, opts ...server.SubscriberOption) error

RegisterSubscriber is syntactic sugar for registering a subscriber.

Types

type Event

type Event interface {
	// Publish publishes a message to the event topic
	Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error
}

Event is used to publish messages to a topic.

func NewEvent

func NewEvent(topic string, c client.Client) Event

NewEvent creates a new event publisher.

type Group

type Group = service.Group

Group is a set of services that share lifecycle management.

func NewGroup

func NewGroup(svcs ...Service) *Group

NewGroup creates a service group for running multiple services in a single binary with shared lifecycle management.

type Option

type Option = service.Option

type Options

type Options = service.Options

type Publisher

type Publisher = Event

Type alias to satisfy the deprecation.

type Service

type Service = service.Service

Service is the interface for a go-micro service.

func FromContext

func FromContext(ctx context.Context) (Service, bool)

FromContext retrieves a Service from the Context.

func New

func New(name string, opts ...Option) Service

New creates a new service with the given name and options.

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

func NewService

func NewService(opts ...Option) Service

NewService creates and returns a new Service based on the packages within. Deprecated: Use New(name, opts...) instead.

Directories

Path Synopsis
Package auth provides authentication and authorization capability
Package auth provides authentication and authorization capability
noop
Package noop provides a no-op auth implementation for testing and development.
Package noop provides a no-op auth implementation for testing and development.
jwt module
Package broker is an interface used for asynchronous messaging
Package broker is an interface used for asynchronous messaging
nats module
Package client is an interface for an RPC client
Package client is an interface for an RPC client
grpc module
cmd
Package cmd is an interface for parsing the command line
Package cmd is an interface for parsing the command line
micro command
micro/api
Package api implements the 'micro api' command — a lightweight HTTP-to-RPC gateway that proxies JSON requests to go-micro services.
Package api implements the 'micro api' command — a lightweight HTTP-to-RPC gateway that proxies JSON requests to go-micro services.
micro/cli/build
Package build provides the micro build command for building service binaries
Package build provides the micro build command for building service binaries
micro/cli/deploy
Package deploy provides the micro deploy command for deploying services
Package deploy provides the micro deploy command for deploying services
micro/cli/gen
Package generate provides code generation commands for micro
Package generate provides code generation commands for micro
micro/cli/init
Package initcmd provides the micro init command for server setup
Package initcmd provides the micro init command for server setup
micro/cli/new
Package new generates micro service templates
Package new generates micro service templates
micro/cli/remote
Package remote provides remote server operations for micro
Package remote provides remote server operations for micro
micro/cli/util
Package cliutil contains methods used across all cli commands @todo: get rid of os.Exits and use errors instread
Package cliutil contains methods used across all cli commands @todo: get rid of os.Exits and use errors instread
micro/resource
Package resource provides CLI commands that map directly onto go-micro's core interfaces — registry, broker, store, and config.
Package resource provides CLI commands that map directly onto go-micro's core interfaces — registry, broker, store, and config.
micro/run/config
Package config handles micro.mu and micro.json configuration parsing
Package config handles micro.mu and micro.json configuration parsing
micro/run/watcher
Package watcher provides file watching for hot reload
Package watcher provides file watching for hot reload
protoc-gen-micro command
protoc-gen-micro is a plugin for the Google protocol buffer compiler to generate Go code.
protoc-gen-micro is a plugin for the Google protocol buffer compiler to generate Go code.
protoc-gen-micro-gateway command
protoc-gen-micro-gateway generates gateway HTTP rules (gateway/SPEC.md section 2.2) from google.api.http annotations: for each .proto file with annotated methods, a <file>.gateway.yaml next to it (relative to the output directory) holding an http_rules list to merge into the gateway rules document.
protoc-gen-micro-gateway generates gateway HTTP rules (gateway/SPEC.md section 2.2) from google.api.http annotations: for each .proto file with annotated methods, a <file>.gateway.yaml next to it (relative to the output directory) holding an http_rules list to merge into the gateway rules document.
protoc-gen-micro/generator
The code generator for the plugin for the Google protocol buffer compiler.
The code generator for the plugin for the Google protocol buffer compiler.
Package codec is an interface for encoding messages
Package codec is an interface for encoding messages
bytes
Package bytes provides a bytes codec which does not encode or decode anything
Package bytes provides a bytes codec which does not encode or decode anything
grpc
Package grpc provides a grpc codec
Package grpc provides a grpc codec
json
Package json provides a json codec
Package json provides a json codec
jsonrpc
Package jsonrpc provides a json-rpc 1.0 codec
Package jsonrpc provides a json-rpc 1.0 codec
proto
Package proto provides a proto codec
Package proto provides a proto codec
protorpc
Protorpc provides a net/rpc proto-rpc codec.
Protorpc provides a net/rpc proto-rpc codec.
text
Package text reads any text/* content-type
Package text reads any text/* content-type
Package config is an interface for dynamic configuration.
Package config is an interface for dynamic configuration.
encoder
Package encoder handles source encoding formats
Package encoder handles source encoding formats
loader
Package loader manages loading from multiple sources
Package loader manages loading from multiple sources
reader
Package reader parses change sets and provides config values
Package reader parses change sets and provides config values
secrets
Package secrets is an interface for encrypting and decrypting secrets
Package secrets is an interface for encrypting and decrypting secrets
secrets/box
Package box is an asymmetric implementation of config/secrets using nacl/box
Package box is an asymmetric implementation of config/secrets using nacl/box
secrets/secretbox
Package secretbox is a config/secrets implementation that uses nacl/secretbox to do symmetric encryption / verification
Package secretbox is a config/secrets implementation that uses nacl/secretbox to do symmetric encryption / verification
source
Package source is the interface for sources
Package source is the interface for sources
source/file
Package file is a file source.
Package file is a file source.
source/memory
Package memory is a memory source
Package memory is a memory source
debug
handler
Package handler implements service debug handler embedded in go-micro services
Package handler implements service debug handler embedded in go-micro services
log
Package log provides debug logging
Package log provides debug logging
log/memory
Package memory provides an in memory log buffer
Package memory provides an in memory log buffer
profile
Package profile is for profilers
Package profile is for profilers
profile/http
Package http enables the http profiler
Package http enables the http profiler
profile/pprof
Package pprof provides a pprof profiler
Package pprof provides a pprof profiler
stats
Package stats provides runtime stats
Package stats provides runtime stats
trace
Package trace provides an interface for distributed tracing
Package trace provides an interface for distributed tracing
Package errors provides a way to return detailed information for an RPC request error.
Package errors provides a way to return detailed information for an RPC request error.
Package events is for event streaming and storage
Package events is for event streaming and storage
examples
multi-service command
Multi-service example: run multiple services in a single binary.
Multi-service example: run multiple services in a single binary.
gateway
api
Package api provides HTTP API gateway functionality for go-micro services.
Package api provides HTTP API gateway functionality for go-micro services.
push
Package push sends messages to WebSocket clients connected to a gateway (gateway/SPEC.md section 2.3).
Package push sends messages to WebSocket clients connected to a gateway (gateway/SPEC.md section 2.3).
Package health provides health check functionality for microservices.
Package health provides health check functionality for microservices.
internal
test
Package test implements a testing framwork, and provides default tests.
Package test implements a testing framwork, and provides default tests.
util/jitter
Package jitter provides a random jitter
Package jitter provides a random jitter
util/pool
Package pool is a connection pool
Package pool is a connection pool
util/ring
Package ring provides a simple ring buffer for storing local data
Package ring provides a simple ring buffer for storing local data
util/socket
Package socket provides a pseudo socket
Package socket provides a pseudo socket
Package log provides a log interface
Package log provides a log interface
Package metadata is a way of defining message headers
Package metadata is a way of defining message headers
Package model is an interface for structured data storage with schema awareness.
Package model is an interface for structured data storage with schema awareness.
memory
Package memory provides an in-memory model.Model implementation.
Package memory provides an in-memory model.Model implementation.
Package mdns is a multicast dns registry
Package mdns is a multicast dns registry
cache
Package cache provides a registry cache
Package cache provides a registry cache
nacos module
Package selector is a way to pick a list of service nodes
Package selector is a way to pick a list of service nodes
p2c
Package p2c implements power-of-two-choices load balancing with EWMA latency feedback: each pick samples two random nodes and routes to the one with the lower load (ewma_latency × (inflight+1)).
Package p2c implements power-of-two-choices load balancing with EWMA latency feedback: each pick samples two random nodes and routes to the one with the lower load (ewma_latency × (inflight+1)).
weighted
Package weighted implements weight-based node selection for canary / gray releases.
Package weighted implements weight-based node selection for canary / gray releases.
Package server is an interface for a micro server
Package server is an interface for a micro server
grpc module
profile
Package profile provides grouped plugin profiles for go-micro
Package profile provides grouped plugin profiles for go-micro
Package store is an interface for distributed data storage.
Package store is an interface for distributed data storage.
Package sync provides distributed coordination primitives: locks and leader election.
Package sync provides distributed coordination primitives: locks and leader election.
Package transport is an interface for synchronous connection based communication
Package transport is an interface for synchronous connection based communication
headers
headers is a package for internal micro global constants
headers is a package for internal micro global constants
util
addr
addr provides functions to retrieve local IP addresses from device interfaces.
addr provides functions to retrieve local IP addresses from device interfaces.
backoff
Package backoff provides backoff functionality
Package backoff provides backoff functionality
net
tls
Package tls provides TLS utilities for go-micro.
Package tls provides TLS utilities for go-micro.
Package web provides a web service for go-micro
Package web provides a web service for go-micro

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL