go-emqx

module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2026 License: MIT

README ΒΆ

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

go-emqx

Golang client and tools to work with EMQX MQTT message system.


CHINESE README

δΈ­ζ–‡θ―΄ζ˜Ž

Main Features

πŸ”Œ HTTP Client: Publish messages through EMQX dashboard API πŸ“‘ Event Types: Handle client connection and disconnection events πŸ”§ Template Generation: Generate SQL and JSON templates when setting EMQX rules πŸ”— Webhook Support: Process EMQX webhook events in applications

Installation

go get github.com/yylego/go-emqx
Prerequisites
  • EMQX message system instance (version 5.x)

Usage

Publishing Messages
package main

import (
    "context"
    "github.com/yylego/go-emqx/emqxgo"
    "github.com/yylego/rese"
)

func main() {
    // Create HTTP client to work with EMQX dashboard API
    client := emqxgo.NewEmqxHttpClient(&emqxgo.Config{
        BaseUrl:     "http://127.0.0.1:18083",
        ApiUsername: "api-key-here",
        ApiPassword: "api-secret-here",
    })

    // Publish single message
    message := &emqxgo.PublishMessage{
        Payload:         `{"msg":"hello"}`,
        PayloadEncoding: "plain",
        Qos:             1,
        Topic:           "test/topic",
    }

    result := rese.V1(client.Publish(context.Background(), message))
    // Use result...
}

⬆️ Source: Source

Publishing Bulk Messages
// Publish messages at once
var messages []*emqxgo.PublishBulkMessage
for i := 0; i < 3; i++ {
    messages = append(messages, &emqxgo.PublishBulkMessage{
        Payload:         `{"index":` + fmt.Sprint(i) + `}`,
        PayloadEncoding: "plain",
        Qos:             1,
        Topic:           "test/topic",
    })
}

results := rese.V1(client.PublishBulk(context.Background(), messages))
// Use results...

⬆️ Source: Source

Receiving Connection Events
import (
    "github.com/gin-gonic/gin"
    "github.com/yylego/go-emqx/emqxgo"
)

func main() {
    engine := gin.New()

    // Handle client connected event
    engine.POST("/events/connected", func(c *gin.Context) {
        var event emqxgo.ConnectedEvent
        if err := c.BindJSON(&event); err != nil {
            c.JSON(400, gin.H{"error": err.Error()})
            return
        }
        // Process connected event
        c.JSON(200, gin.H{"status": "ok"})
    })

    // Handle client disconnected event
    engine.POST("/events/disconnected", func(c *gin.Context) {
        var event emqxgo.DisconnectedEvent
        if err := c.BindJSON(&event); err != nil {
            c.JSON(400, gin.H{"error": err.Error()})
            return
        }
        // Process disconnected event
        c.JSON(200, gin.H{"status": "ok"})
    })

    engine.Run(":8080")
}
Generating EMQX Rule Templates
import (
    "github.com/yylego/go-emqx/emqxeventtemplate"
    "github.com/yylego/go-emqx/emqxgo"
)

func main() {
    // Generate SQL when configuring EMQX rules
    sql := emqxeventtemplate.GetEmqxEventFieldSQL(
        emqxgo.ConnectedEvent{},
        "$events/client/connected",
    )
    // Output: SELECT clientid, username, ... FROM "$events/client/connected"

    // Generate JSON template as webhook data
    template := emqxeventtemplate.GetEmqxEventTemplate(
        emqxgo.ConnectedEvent{},
    )
    // Output: {"clientid": "${clientid}", "username": "${username}", ...}
}

API Reference

emqxgo Package

Types:

  • EmqxHttpClient - HTTP client to work with EMQX dashboard API
  • Config - Configuration when creating HTTP client
  • PublishMessage - Single message publish request
  • PublishBulkMessage - Bulk message publish request
  • ConnectedEvent - Client connection event
  • DisconnectedEvent - Client disconnection event

Functions:

  • NewEmqxHttpClient(config *Config) *EmqxHttpClient - Create HTTP client
  • Publish(ctx context.Context, message *PublishMessage) (*PublishResult, error) - Publish single message
  • PublishBulk(ctx context.Context, messages []*PublishBulkMessage) ([]*PublishBulkResult, error) - Publish bulk messages
emqxeventtemplate Package

Functions:

  • GetEmqxEventFieldSQL(object any, eventName string) string - Generate SQL select statement
  • GetEmqxEventTemplate(object any) string - Generate JSON template

EMQX Configuration

Setup Dashboard API Credentials
  1. Access EMQX dashboard: http://localhost:18083
  2. Navigate to: System β†’ API Credentials
  3. Create new API credentials with required permissions
  4. Use the credentials in the client configuration
Configure Webhook
  1. Create HTTP connection pointing to the endpoint
  2. Create rules to match events (e.g., $events/client/connected)
  3. Use generated SQL and JSON template from this package
  4. Set action to send events to the webhook endpoint

Examples

See the internal/demos path to find complete examples:

  • demo1x - Basic publish example with MQTT subscription
  • demo2x - Bulk publish with message tracking

See the internal/sketches path to find webhook endpoint example:

  • sketch1 - HTTP endpoint receiving EMQX events and authentication

EMQX Documentation

πŸ“„ License

MIT License. See LICENSE.


🀝 Contributing

Contributions are welcome! Report bugs, suggest features, and contribute code:

  • πŸ› Found a mistake? Open an issue on GitHub with reproduction steps
  • πŸ’‘ Have a feature idea? Create an issue to discuss the suggestion
  • πŸ“– Documentation confusing? Report it so we can improve
  • πŸš€ Need new features? Share the use cases to help us understand requirements
  • ⚑ Performance issue? Help us optimize through reporting slow operations
  • πŸ”§ Configuration problem? Ask questions about complex setups
  • πŸ“’ Follow project progress? Watch the repo to get new releases and features
  • 🌟 Success stories? Share how this package improved the workflow
  • πŸ’¬ Feedback? We welcome suggestions and comments

πŸ”§ Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage UI).
  2. Clone: Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate: Navigate to the cloned project (cd repo-name)
  4. Branch: Create a feature branch (git checkout -b feature/xxx).
  5. Code: Implement the changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and follow Go code style conventions
  7. Documentation: Update documentation to support client-facing changes and use significant commit messages
  8. Stage: Stage changes (git add .)
  9. Commit: Commit changes (git commit -m "Add feature xxx") ensuring backward compatible code
  10. Push: Push to the branch (git push origin feature/xxx).
  11. PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.

Please ensure tests pass and include relevant documentation updates.


🌟 Support

Welcome to contribute to this project via submitting merge requests and reporting issues.

Project Support:

  • ⭐ Give GitHub stars if this project helps you
  • 🀝 Share with teammates and (golang) programming friends
  • πŸ“ Write tech blogs about development tools and workflows - we provide content writing support
  • 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene

Have Fun Coding with this package! πŸŽ‰πŸŽ‰πŸŽ‰


GitHub Stars

Stargazers

Directories ΒΆ

Path Synopsis
Package emqxeventtemplate provides utilities to generate EMQX rule templates Creates SQL select statements and JSON templates from Go struct definitions Eliminates hand-coded field mapping when configuring EMQX data integration rules Use with ConnectedEvent and DisconnectedEvent to auto-generate webhook configurations
Package emqxeventtemplate provides utilities to generate EMQX rule templates Creates SQL select statements and JSON templates from Go struct definitions Eliminates hand-coded field mapping when configuring EMQX data integration rules Use with ConnectedEvent and DisconnectedEvent to auto-generate webhook configurations
Package emqxgo provides HTTP client and utilities for EMQX MQTT broker integration Enables message publishing via EMQX dashboard API and webhook event handling Supports both single and bulk message publishing operations
Package emqxgo provides HTTP client and utilities for EMQX MQTT broker integration Enables message publishing via EMQX dashboard API and webhook event handling Supports both single and bulk message publishing operations
internal
demos/demo1x command
Package main demonstrates basic EMQX HTTP API usage with MQTT subscription Shows how to subscribe to MQTT topic and publish messages via HTTP API
Package main demonstrates basic EMQX HTTP API usage with MQTT subscription Shows how to subscribe to MQTT topic and publish messages via HTTP API
demos/demo2x command
Package main demonstrates bulk message publishing with message tracking Shows how to publish messages at once and track received count
Package main demonstrates bulk message publishing with message tracking Shows how to publish messages at once and track received count
sketches/sketch1 command
Package main provides HTTP webhook server to receive EMQX events Handles client connection, disconnection, and authentication events
Package main provides HTTP webhook server to receive EMQX events Handles client connection, disconnection, and authentication events
utils
Package utils provides common functions used in demos and sketches Contains UUID generation, pointer conversion, and authentication token functions
Package utils provides common functions used in demos and sketches Contains UUID generation, pointer conversion, and authentication token functions

Jump to

Keyboard shortcuts

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