asyncapi

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

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 5 Imported by: 0

README

🚀 AsyncAPI-Go

Code-First AsyncAPI v3 Documentation & Embedded UI for Go

Go Reference AsyncAPI v3.0.0


Writing and maintaining massive AsyncAPI YAML files by hand is tedious and error-prone. In fast-moving event-driven architectures, documentation often drifts from the actual codebase.

AsyncAPI-Go solves this. It is a zero-dependency library that uses Go reflection to instantly generate valid AsyncAPI v3 documentation directly from your Go structs. Better yet, it includes a built-in HTTP handler to serve the beautiful, interactive @asyncapi/react-component UI right from your microservice.

No YAML. No drift. Just your code.

✨ Why use this?

  • Code-First Generation: Automatically maps Go primitives, time.Time, and complex nested structs to valid JSON Schema.
  • Embedded UI Server: Serve world-class API documentation directly from your Go app with a single line of code.
  • Smart Struct Tags: Extracts clean description tags for the UI, while preserving critical backend tags (validate, db, json) in a custom x-go-tags extension for total visibility.
  • Robust Security Schemes: Native builder methods for Kafka SASL, JWT Bearer tokens, HTTP Basic Auth, and API Keys.
  • Zero Dependencies: Built entirely with the standard library.

📦 Installation

go get github.com/Generalsimus/asyncapi-go

🚀 Quick Start

Get a fully documented Kafka event stream and a beautiful UI running in under 40 lines of code.

First, define your event payload as a standard Go struct.

func main() {
    doc := asyncapi.NewAsyncAPI("User Pipeline", "1.0.0", "Kafka Event Driven Service")

    // Define a Secure Kafka Broker
    doc.AddServer("kafka-prod", "kafka.internal.net:9092", "kafka", "Prod Cluster").
        SetKafkaSASL("SCRAM-SHA-256 Authentication")

    // Define the Topic (Channel) and Payload
    signupChan := doc.AddChannel("user.events.signup", "Emitted when a new user registers")
    signupChan.AddMessage(&UserSignup{})

    // The Server publishes to this topic
    doc.AddOperation(signupChan, "send").SetKafkaConsumerGroup("user-group")

    http.HandleFunc("/docs", doc.Handler)
    http.ListenAndServe(":8080", nil)
}

2. RabbitMQ (Message Queuing / AMQP)

Perfect for task processing and worker queues.

type ProcessPayment struct {
    PaymentID string  `json:"payment_id"`
    Amount    float64 `json:"amount"`
}

func main() {
    doc := asyncapi.NewAsyncAPI("Payment Gateway", "1.2.0", "RabbitMQ Task Queue")

    // Define an AMQP Server with Basic Auth
    doc.AddServer("rmq-prod", "amqp.example.com:5672", "amqp", "Main RabbitMQ Node").
        SetBasicAuth("Requires RabbitMQ username and password")

    paymentChan := doc.AddChannel("payments.process", "Queue to handle incoming payments")
    paymentChan.AddMessage(&ProcessPayment{})

    // The Worker consumes from this queue
    doc.AddOperation(paymentChan, "receive")

    http.HandleFunc("/docs", doc.Handler)
    http.ListenAndServe(":8080", nil)
}

3. WebSockets (Real-time Client/Server)

Perfect for live market data, chat applications, and mobile clients.

type LiveTicker struct {
    Symbol string  `json:"symbol"`
    Price  float64 `json:"price"`
}

func main() {
    doc := asyncapi.NewAsyncAPI("Market Data API", "2.0.0", "WebSocket Streaming Server")

    // Define a Secure WebSocket Server
    doc.AddServer("ws-gateway", "wss://api.example.com/ws", "wss", "Public WebSocket Gateway").
        SetJWTAuth("Requires Bearer Token during connection handshake")

    tickerChan := doc.AddChannel("market.ticker.live", "Real-time price updates")
    tickerChan.AddMessage(&LiveTicker{})

    // The Server pushes events to the Client
    doc.AddOperation(tickerChan, "receive")

    http.HandleFunc("/docs", doc.Handler)
    http.ListenAndServe(":8080", nil)
}

4. HTTP / RPC (Request & Reply Pattern)

You can seamlessly map Request-Reply patterns natively, which is vital for B2B Webhooks or RPC calls over message brokers.

// 1. Define Request and Response Channels
reqChan := doc.AddChannel("v1/orders/request", "Submit an order")
reqChan.AddMessage(&OrderRequest{})

resChan := doc.AddChannel("v1/orders/response", "Receive the order status")
resChan.AddMessage(&OrderResponse{})

// 2. Link the POST request directly to the expected reply
doc.AddHttpOperation(reqChan, "send", "POST").SetReply(resChan)

🔒 Supported Security Architectures

The framework provides fluent builder methods to attach standard security protocols directly to your servers, rendering beautiful, standard-compliant UI badges:

  • SetKafkaSASL(description string): Generates scramSha256 Kafka properties.
  • SetJWTAuth(description string): Generates HTTP Bearer configuration.
  • SetAPIKeyAuth(headerName, description string): Generates HTTP API Key configuration.
  • SetBasicAuth(description string): Generates standard HTTP Username/Password configuration.

🤝 Contributing

Pull requests are welcome! For major changes, please open an issue first to discuss what you would like to change.

If you are adding support for a new protocol binding (e.g., MQTT or SQS), please ensure you test the UI rendering via the doc.Handler.

📄 License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Generate

func Generate(t reflect.Type, description string) map[string]any

Generate recursively builds a JSON schema map from a reflected Go type.

Types

type AsyncAPIDocument

type AsyncAPIDocument struct {
	AsyncAPI   string                `json:"asyncapi"`
	Info       AsyncAPIInfo          `json:"info"`
	Servers    map[string]*Server    `json:"servers,omitempty"`
	Channels   map[string]*Channel   `json:"channels,omitempty"`
	Operations map[string]*Operation `json:"operations,omitempty"`
	Components *Components           `json:"components,omitempty"`
}

func NewAsyncAPI

func NewAsyncAPI(title, version, description string) *AsyncAPIDocument

NewAsyncAPI initializes a new AsyncAPI v3 document.

func (*AsyncAPIDocument) AddChannel

func (doc *AsyncAPIDocument) AddChannel(address, description string) *Channel

AddChannel registers a new topic, queue, or endpoint.

func (*AsyncAPIDocument) AddHttpOperation

func (doc *AsyncAPIDocument) AddHttpOperation(channel *Channel, action string, httpMethod string) *Operation

AddHttpOperation safely links an action and defines the HTTP method binding.

func (*AsyncAPIDocument) AddOperation

func (doc *AsyncAPIDocument) AddOperation(channel *Channel, action string) *Operation

AddOperation links an action (send or receive) to a registered channel.

func (*AsyncAPIDocument) AddServer

func (doc *AsyncAPIDocument) AddServer(serverKey, host, protocol, description string) *Server

AddServer registers a new message broker or web server to the documentation.

func (*AsyncAPIDocument) GenerateHtml

func (doc *AsyncAPIDocument) GenerateHtml() string

GenerateHtml returns the full HTML string containing the AsyncAPI React component.

func (*AsyncAPIDocument) Handler

func (doc *AsyncAPIDocument) Handler(w http.ResponseWriter, r *http.Request)

Handler is a standard HTTP handler function to serve the AsyncAPI UI.

type AsyncAPIInfo

type AsyncAPIInfo struct {
	Title       string `json:"title"`
	Version     string `json:"version"`
	Description string `json:"description,omitempty"`
}

type Channel

type Channel struct {
	Address     string              `json:"address"`
	Description string              `json:"description,omitempty"`
	Messages    map[string]*Message `json:"messages,omitempty"`
}

func (*Channel) AddMessage

func (c *Channel) AddMessage(payload any) *Message

AddMessage reflects on a Go struct to automatically generate the payload schema.

type ChannelRef

type ChannelRef struct {
	Ref string `json:"$ref"`
}

type Components

type Components struct {
	Messages        map[string]*Message        `json:"messages,omitempty"`
	SecuritySchemes map[string]*SecurityScheme `json:"securitySchemes,omitempty"`
}

type KafkaConsumerGroupIDSchema

type KafkaConsumerGroupIDSchema struct {
	Type    string   `json:"type,omitempty"`
	Enum    []string `json:"enum,omitempty"`
	GroupID string   `json:"-"`
}

type Message

type Message struct {
	Name           string         `json:"name,omitempty"`
	Title          string         `json:"title,omitempty"`
	Payload        map[string]any `json:"payload"`
	ChannelAddress string         `json:"-"`
}

type Operation

type Operation struct {
	Action   string          `json:"action"` // "send" or "receive"
	Channel  *ChannelRef     `json:"channel"`
	Bindings map[string]any  `json:"bindings,omitempty"`
	Reply    *OperationReply `json:"reply,omitempty"`
}

func (*Operation) SetKafkaConsumerGroup

func (op *Operation) SetKafkaConsumerGroup(groupID string) *KafkaConsumerGroupIDSchema

SetKafkaConsumerGroup safely links a consumer group ID to the operation and returns the schema object for direct access.

func (*Operation) SetReply

func (op *Operation) SetReply(replyChannel *Channel) *Operation

SetReply links a response channel to the current operation to establish a Request-Reply pattern.

type OperationReply

type OperationReply struct {
	Channel *ChannelRef `json:"channel"`
}

type SecurityScheme

type SecurityScheme struct {
	Type        string `json:"type"`
	Description string `json:"description,omitempty"`
	Scheme      string `json:"scheme,omitempty"`
	In          string `json:"in,omitempty"`
	Name        string `json:"name,omitempty"`
}

type Server

type Server struct {
	Host        string            `json:"host"`
	Protocol    string            `json:"protocol"`
	Description string            `json:"description,omitempty"`
	Bindings    map[string]any    `json:"bindings,omitempty"`
	Security    []*SecurityScheme `json:"security,omitempty"`
}

func (*Server) SetAPIKeyAuth

func (s *Server) SetAPIKeyAuth(headerName, description string) *Server

SetAPIKeyAuth configures API Key authentication injected via headers.

func (*Server) SetBasicAuth

func (s *Server) SetBasicAuth(description string) *Server

SetBasicAuth configures standard HTTP Basic Authentication (Username/Password).

func (*Server) SetJWTAuth

func (s *Server) SetJWTAuth(description string) *Server

SetJWTAuth configures standard HTTP Bearer (JWT) authentication.

func (*Server) SetKafkaSASL

func (s *Server) SetKafkaSASL(description string) *Server

SetKafkaSASL configures SCRAM-SHA-256 authentication for a Kafka server.

Jump to

Keyboard shortcuts

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