
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
- Access EMQX dashboard:
http://localhost:18083
- Navigate to: System β API Credentials
- Create new API credentials with required permissions
- Use the credentials in the client configuration
- Create HTTP connection pointing to the endpoint
- Create rules to match events (e.g.,
$events/client/connected)
- Use generated SQL and JSON template from this package
- 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:
- Fork: Fork the repo on GitHub (using the webpage UI).
- Clone: Clone the forked project (
git clone https://github.com/yourname/repo-name.git).
- Navigate: Navigate to the cloned project (
cd repo-name)
- Branch: Create a feature branch (
git checkout -b feature/xxx).
- Code: Implement the changes with comprehensive tests
- Testing: (Golang project) Ensure tests pass (
go test ./...) and follow Go code style conventions
- Documentation: Update documentation to support client-facing changes and use significant commit messages
- Stage: Stage changes (
git add .)
- Commit: Commit changes (
git commit -m "Add feature xxx") ensuring backward compatible code
- Push: Push to the branch (
git push origin feature/xxx).
- 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
