go-kit

module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2026 License: MIT

README

go-kit — Go Microservice Framework

Go Version License

Modern, production-ready Go microservice framework with AI-first design. Built for developers who want clear architecture without the boilerplate.

Core Pillars

  1. Clear Architecture: Enforces a clean separation between Transport, Endpoint, and Service layers. Uses modern Go features like any and generics for maximum flexibility and type safety.
  2. microgen: A powerful code generator that turns definitions (Protobuf, IDL, or DB Schema) into complete, runnable services in seconds.
  3. AI-Ready (Skills): Built-in support for generating AI-tool definitions (OpenAI Tool & MCP compatible). Your microservices can be instantly used by AI agents as "Skills."

Quick Start (30 Seconds)

Define a service in one file and run it.

package main

import (
    "context"
    "github.com/dreamsxin/go-kit/kit"
)

type HelloReq  struct { Name string `json:"name"` }
type HelloResp struct { Message string `json:"message"` }

func main() {
    svc := kit.New(":8080")

    // kit.JSON[Req] creates a typed JSON handler — automatic decode/encode with generics.
    // Use svc.Handle to register it and apply service-level middleware.
    svc.Handle("/hello", kit.JSON[HelloReq](func(ctx context.Context, req HelloReq) (any, error) {
        return HelloResp{Message: "Hello, " + req.Name + "!"}, nil
    }))

    svc.Run()
}
With Middleware
svc := kit.New(":8080",
    kit.WithRateLimit(100),           // 100 req/s
    kit.WithCircuitBreaker(5),        // open after 5 consecutive failures
    kit.WithTimeout(5*time.Second),
    kit.WithRequestID(),              // inject X-Request-ID
    kit.WithLogging(logger),
    kit.WithMetrics(&metrics),
)
With gRPC
svc := kit.New(":8080", kit.WithGRPC(":8081"))

// Register your proto-generated service implementation
pb.RegisterGreeterServer(svc.GRPCServer(), &myGreeter{})

svc.Run() // starts both HTTP and gRPC, graceful shutdown on SIGINT/SIGTERM

Three-Layer Architecture

go-kit enforces a clean separation of concerns:

┌─────────────────────────────────────────────────────┐
│  Transport  (HTTP / gRPC)                           │
│  Decodes requests, encodes responses, routes calls  │
├─────────────────────────────────────────────────────┤
│  Endpoint   (middleware chain)                      │
│  Logging, metrics, rate limiting, circuit breaking  │
├─────────────────────────────────────────────────────┤
│  Service    (pure business logic)                   │
│  No framework imports, fully testable in isolation  │
└─────────────────────────────────────────────────────┘

Each layer has a single responsibility:

  • Service — implements your domain logic as a plain Go interface.
  • Endpoint — wraps each service method as func(ctx, request) (response, error), where middleware is composed.
  • Transport — maps HTTP/gRPC requests to endpoints and back.

The kit package provides a zero-boilerplate shortcut for prototyping. For production services, use microgen to generate the full three-layer structure.


Code Generation (microgen)

microgen automates the boring parts of microservice development.

Installation
go install github.com/dreamsxin/go-kit/cmd/microgen@latest
Modes of Operation
1. From Protobuf (.proto)

Generate full HTTP/gRPC services from your contract.

microgen -idl service.proto -out . -import example.com/mysvc -protocols http,grpc
2. From IDL (.go)

Define a Go interface, and let microgen build the rest.

microgen -idl idl.go -out . -import example.com/mysvc
3. From Database (Reverse Engineering)

Generate a full CRUD service including GORM models and Repositories from an existing DB.

microgen -from-db -db-driver mysql -db-dsn "user:pass@tcp(localhost:3306)/dbname"
Key Features
  • AI Skill Generation: Use the -skill flag to generate a /skill endpoint for AI agents.
  • Client SDK: Automatically generates a ready-to-use Go client for your service.
  • Middleware: Built-in support for Circuit Breakers, Rate Limiting, and Logging.
  • Multi-service: Supports generating multiple services into a single module with unique filenames.

AI & MCP Integration

go-kit is designed for the agentic era. By enabling the Skill feature, your service exposes a machine-readable definition of all its capabilities:

  • OpenAI Tool Format: Accessible via GET /skill
  • MCP (Model Context Protocol): Accessible via GET /skill?format=mcp

This allows an AI agent (like Accio or Claude) to "see" your service methods as tools it can call to perform actions or fetch data.


Project Structure

A generated go-kit project follows this industry-standard layout:

.
├── cmd/main.go          # Entry point, wires everything together
├── service/<svcname>/   # Pure business logic (the "What")
├── endpoint/<svcname>/  # Go-kit Endpoints (the "How" - middleware, logic wrapping)
├── transport/<svcname>/ # HTTP/gRPC handlers (the "Where" - protocol specific)
├── pb/                  # (Optional) Protobuf generated code
├── model/               # (Optional) GORM database models
├── repository/          # (Optional) Data access layer
├── sdk/<svcname>sdk/    # Generated client SDK for other services to use
└── skill/               # AI Tool definitions

License

MIT

Directories

Path Synopsis
cmd
microgen command
microgen/dbschema
Package dbschema 连接数据库,内省表结构,并将其转换为 parser.ParseResult, 供 generator 直接生成完整的 RESTful 微服务代码。
Package dbschema 连接数据库,内省表结构,并将其转换为 parser.ParseResult, 供 generator 直接生成完整的 RESTful 微服务代码。
Package endpoint defines the core Endpoint type and related helpers.
Package endpoint defines the core Endpoint type and related helpers.
examples
best_practice command
Package main demonstrates go-kit best practices:
Package main demonstrates go-kit best practices:
httpclient command
Package main demonstrates the HTTP client components:
Package main demonstrates the HTTP client components:
middleware command
Package main demonstrates every endpoint middleware in the framework:
Package main demonstrates every endpoint middleware in the framework:
profilesvc/client
Package client provides a profilesvc client backed by Consul service discovery, round-robin load balancing, and automatic retry.
Package client provides a profilesvc client backed by Consul service discovery, round-robin load balancing, and automatic retry.
quickstart command
Package quickstart is the minimal go-kit HTTP service.
Package quickstart is the minimal go-kit HTTP service.
sd command
Package main demonstrates the service-discovery (sd) components without any external dependency (no Consul, no network):
Package main demonstrates the service-discovery (sd) components without any external dependency (no Consul, no network):
Package kit provides a high-level, zero-boilerplate API for rapid prototyping and production microservices.
Package kit provides a high-level, zero-boilerplate API for rapid prototyping and production microservices.
Package log provides a thin wrapper around go.uber.org/zap.
Package log provides a thin wrapper around go.uber.org/zap.
sd
Package sd provides service-discovery helpers that wire together an Instancer, EndpointCache, Balancer, and Retry executor into a single callable endpoint.Endpoint.
Package sd provides service-discovery helpers that wire together an Instancer, EndpointCache, Balancer, and Retry executor into a single callable endpoint.Endpoint.
grpc/client
Package client provides a gRPC transport client that wraps a gRPC connection as an endpoint.Endpoint.
Package client provides a gRPC transport client that wraps a gRPC connection as an endpoint.Endpoint.
grpc/server
Package server provides a gRPC transport server that bridges the framework's Endpoint abstraction to the gRPC protocol.
Package server provides a gRPC transport server that bridges the framework's Endpoint abstraction to the gRPC protocol.
http/server
Package server provides an HTTP transport server that bridges the framework's Endpoint abstraction to the standard net/http package.
Package server provides an HTTP transport server that bridges the framework's Endpoint abstraction to the standard net/http package.

Jump to

Keyboard shortcuts

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