### Basic KSMUX HTTP Server Setup in Go
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
This example demonstrates how to initialize a KSMUX router, define a simple GET route for the root path, and start the HTTP server. It showcases the minimal code required to get a basic web application running with KSMUX.
```go
package main
import "github.com/kamalshkeir/ksmux"
func main() {
// Create a new router
router := ksmux.New(ksmux.Confif{
Address:"localhost:9313",
})
// Define a route
router.Get("/", func(c *ksmux.Context) {
c.Text("Hello World!")
})
// Start the server
router.Run()
}
```
--------------------------------
### Getting Started Server Command
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/README.md
Command to start the ksmux pub/sub server.
```bash
go run cmd/main.go
```
--------------------------------
### Go Server Setup and Pub/Sub Operations
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/README.md
Demonstrates how to set up a ksmux pub/sub server in Go, including subscribing to topics, publishing messages with acknowledgment, and starting the server.
```Go
package main
import (
"fmt"
"time"
"github.com/kamalshkeir/ksmux/ksps"
)
func main() {
server := ksps.NewServer()
// Subscribe to messages
server.Subscribe("events", func(data any, unsub func()) {
fmt.Printf("Received: %v\n", data)
})
// Publish with acknowledgment
ack := server.PublishWithAck("events", "Hello World!", 5*time.Second)
responses := ack.Wait()
server.Run() // Start on :9313
}
```
--------------------------------
### Installation Commands for Server and Clients
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/README.md
Provides command-line instructions for installing the ksmux pub/sub server in Go and clients in Python and JavaScript.
```bash
go mod init myapp
go get github.com/kamalshkeir/ksmux/ksps
```
```bash
pip install ksps
```
```html
```
--------------------------------
### Install KSMUX Go Module
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
This command installs the KSMUX Go module using `go get`, fetching the latest version from GitHub. It's the essential first step to integrate KSMUX into any Go project, ensuring all necessary dependencies are downloaded.
```bash
go get github.com/kamalshkeir/ksmux@latest
```
--------------------------------
### Quick Start: Connect, Subscribe, Publish with KSPS Dart
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/dart/README.md
A comprehensive example demonstrating the core functionalities of the KSPS Dart client, including connecting to a server, subscribing to a topic, publishing messages (with and without acknowledgment), and properly closing the client connection.
```Dart
import 'package:ksps_dart/ksps_dart.dart';
void main() async {
// Connect to server
final client = await KspsClient.connect(
ClientConnectOptions(
id: 'my-dart-client',
address: 'localhost:9313',
autorestart: true,
onId: (data, unsub) {
print('Direct message: $data');
},
),
);
// Subscribe to topic
final unsub = client.subscribe('my_topic', (data, unsubFn) {
print('Received: $data');
});
// Publish message
client.publish('my_topic', {'message': 'Hello from Dart!'});
// Publish with acknowledgment
final ack = client.publishWithAck(
'ack_topic',
{'data': 'Important message'},
Duration(seconds: 5),
);
final responses = await ack.wait();
print('ACK responses: ${responses.length}');
// Clean up
unsub();
await client.close();
}
```
--------------------------------
### Define Various Routing Patterns in KSMUX Go
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
This example showcases KSMUX's flexible routing capabilities, including basic HTTP methods (GET, POST, PUT, DELETE), URL parameters for dynamic path segments, and wildcards for matching arbitrary file paths. It illustrates how to extract parameters from the context and serve files based on wildcard matches.
```go
// Basic routes
router.Get("/users", handleUsers)
router.Post("/users", createUser)
router.Put("/users/:id", updateUser)
router.Delete("/users/:id", deleteUser)
// URL parameters
router.Get("/users/:id", func(c *ksmux.Context) {
id := c.Param("id")
c.Json(map[string]string{"id": id})
})
// Wildcards
router.Get("/files/*filepath", serveFiles)
```
--------------------------------
### KSMUX WebSocket Connection Handling
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
Demonstrates how to establish and manage WebSocket connections in KSMUX. It covers upgrading an HTTP connection to a WebSocket, reading incoming messages, and echoing them back to the client, providing a basic example of real-time communication.
```go
router.Get("/ws", func(c *ksmux.Context) {
// Upgrade HTTP connection to WebSocket
conn, err := c.UpgradeConnection()
if err != nil {
return
}
// Handle WebSocket messages
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
return
}
// Echo the message back
err = conn.WriteMessage(messageType, p)
if err != nil {
return
}
}
})
```
--------------------------------
### KSMUX Load Balancer Configuration
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
Illustrates how to set up a basic load balancer in KSMUX to distribute incoming requests across multiple backend servers. The example shows how to define backend options, including their URLs and optional middleware specific to each backend, ensuring high availability and distribution.
```go
func main() {
app := ksmux.New()
err := app.LocalStatics("assets", "/static")
lg.CheckError(err)
err = app.LocalTemplates("temps")
lg.CheckError(err)
// Setup load balancer for /api path, distributing requests between two backend servers
err = app.LoadBalancer("/",
ksmux.BackendOpt{
Url: "localhost:8081",
Middlewares: []ksmux.Handler{
func(c *ksmux.Context) {
fmt.Println("from middleware 8081")
},
},
},
ksmux.BackendOpt{
Url: "localhost:8082",
},
)
lg.CheckError(err)
app.Run(":9313")
}
```
--------------------------------
### KSMUX Static File Serving
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
Demonstrates how to serve static assets like images, CSS, and JavaScript files using KSMUX. It provides examples for serving files from a local directory and from an embedded file system, mapping a URL path to the physical location of the static files.
```go
// Serve local directory
router.LocalStatics("static/", "/static")
// Serve embedded files
router.EmbededStatics(embededFS, "static/", "/static")
```
--------------------------------
### Install KSPS Dart Client via pubspec.yaml
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/dart/README.md
Instructions on how to add the `ksps_dart` package to a Dart or Flutter project's `pubspec.yaml` file, allowing installation from a remote package repository or a local file path for development.
```YAML
dependencies:
ksps_dart: ^1.0.0
```
```YAML
dependencies:
ksps_dart:
path: ../dart
```
--------------------------------
### Flutter KSMUX Client Integration Example
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/dart/README.md
This Dart code snippet demonstrates a complete Flutter `StatefulWidget` that connects to a KSMUX server using `KspsClient`. It shows how to configure connection options, subscribe to direct and topic-based messages, publish data, and manage the client lifecycle within `initState` and `dispose`.
```dart
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State {
KspsClient? _client;
List _messages = [];
@override
void initState() {
super.initState();
_connectToServer();
}
Future _connectToServer() async {
try {
_client = await KspsClient.connect(
ClientConnectOptions(
id: 'flutter-app',
address: 'your-server.com:9313',
secure: true, // Use WSS for production
autorestart: true,
onId: (data, unsub) {
setState(() {
_messages.add('Direct: ${data.toString()}');
});
},
),
);
_client!.subscribe('app_updates', (data, unsub) {
setState(() {
_messages.add('Update: ${data.toString()}');
});
});
} catch (e) {
print('Connection failed: $e');
}
}
void _sendMessage() {
_client?.publish('user_action', {
'action': 'button_pressed',
'timestamp': DateTime.now().toIso8601String(),
});
}
@override
void dispose() {
_client?.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('KSPS Flutter Demo')),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: _messages.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_messages[index]),
);
},
),
),
ElevatedButton(
onPressed: _sendMessage,
child: Text('Send Message'),
),
],
),
);
}
}
```
--------------------------------
### KSMUX Client Error Handling in Dart
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/dart/README.md
This Dart example illustrates robust error handling for the KSMUX client. It demonstrates how to catch connection errors using a `try-catch` block and how to manage message acknowledgments (ACKs), including handling timeouts and processing individual success or error responses from `publishWithAck`.
```dart
try {
final client = await KspsClient.connect(options);
// Use client...
} catch (e) {
print('Connection error: $e');
// Handle connection failure
}
// ACK timeout handling
final ack = client.publishWithAck('topic', data, Duration(seconds: 5));
final responses = await ack.wait();
if (responses.isEmpty) {
print('No ACK responses received (timeout)');
} else {
for (final entry in responses.entries) {
if (!entry.value.success) {
print('ACK error from ${entry.key}: ${entry.value.error}');
}
}
}
```
--------------------------------
### Core Pub/Sub API Methods
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/README.md
Comprehensive documentation for the core API methods available across all ksmux pub/sub clients, covering subscription, publishing, and acknowledgment management.
```APIDOC
Subscribe(topic, callback)
- Description: Subscribes to a specific topic.
- Parameters:
- topic: (string) The name of the topic to subscribe to.
- callback: (function) A function to be called when a message is received on the topic. It typically receives `data` and an `unsub` function.
Unsubscribe(topic)
- Description: Unsubscribes from a specific topic.
- Parameters:
- topic: (string) The name of the topic to unsubscribe from.
Publish(topic, data)
- Description: Publishes data to a specific topic without waiting for acknowledgment.
- Parameters:
- topic: (string) The name of the topic to publish to.
- data: (any) The data payload to send.
PublishToID(targetID, data)
- Description: Publishes data directly to a specific client ID.
- Parameters:
- targetID: (string) The ID of the target client.
- data: (any) The data payload to send.
PublishToServer(addr, data)
- Description: Publishes data to a specific server address.
- Parameters:
- addr: (string) The address of the target server.
- data: (any) The data payload to send.
PublishWithAck(topic, data, timeout)
- Description: Publishes data to a topic and returns an acknowledgment object to manage responses.
- Parameters:
- topic: (string) The name of the topic to publish to.
- data: (any) The data payload to send.
- timeout: (duration/number) The maximum time to wait for acknowledgments (e.g., `time.Second` in Go, milliseconds in JS, seconds in Python).
- Returns: An ACK management object.
PublishToIDWithAck(targetID, data, timeout)
- Description: Publishes data directly to a specific client ID and returns an acknowledgment object.
- Parameters:
- targetID: (string) The ID of the target client.
- data: (any) The data payload to send.
- timeout: (duration/number) The maximum time to wait for acknowledgments.
- Returns: An ACK management object.
ACK Management Methods (on the acknowledgment object):
Wait()
- Description: Waits for all expected acknowledgments to be received or for the timeout to expire.
- Returns: A collection of responses.
WaitAny()
- Description: Waits for the first acknowledgment to be received or for the timeout to expire.
- Returns: The first response and a boolean indicating success.
GetStatus()
- Description: Retrieves the real-time status of the acknowledgment process.
- Returns: Current status information.
IsComplete()
- Description: Checks if all expected acknowledgments have been received.
- Returns: (boolean) True if complete, false otherwise.
Cancel()
- Description: Cancels the waiting process for acknowledgments.
```
--------------------------------
### KSMUX Context Methods for Request/Response Handling
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
Demonstrates various methods available on the `ksmux.Context` object for handling HTTP requests and responses, including sending different content types (text, JSON, HTML), parsing request data (parameters, query, body, cookies), managing HTTP headers, and performing file operations (download, save, serve).
```go
// Response methods
c.Text("Hello") // Send plain text
c.Json(data) // Send JSON
c.JsonIndent(data) // Send indented JSON
c.Html("template.html", data) // Render HTML template
c.Stream("message") // Server-sent events
c.Download(bytes, "file.txt") // Force download
c.Redirect("/new-path") // HTTP redirect
// Request data
c.Param("id") // URL parameter
c.QueryParam("q") // Query parameter
c.BodyJson() // Parse JSON body
c.BodyStruct(&data) // Parse body into struct
c.GetCookie("session") // Get cookie value
c.SetCookie("session", "value") // Set cookie
// Headers
c.SetHeader("X-Custom", "value")
c.AddHeader("X-Custom", "value")
c.SetStatus(200)
// Files
c.SaveFile(fileHeader, "path") // Save uploaded file
c.ServeFile("image/png", "path") // Serve local file
```
--------------------------------
### KSMUX Middleware Implementation
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
Illustrates how to apply middleware globally using `router.Use()` for common functionalities like logging, Gzip compression, and CORS. It also shows how to create and apply route-specific middleware functions, such as an `adminOnly` check, to restrict access to certain routes.
```go
// Global middleware
router.Use(ksmux.Logs())
router.Use(ksmux.Gzip())
router.Use(ksmux.Cors())
// Route-specific middleware
router.Get("/admin", adminOnly(handleAdmin))
func adminOnly(next ksmux.Handler) ksmux.Handler {
return func(c *ksmux.Context) {
if !isAdmin(c) {
c.Status(403).Text("Forbidden")
return
}
next(c)
}
}
```
--------------------------------
### KSMUX HTML Template Rendering
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
Explains how to configure and render HTML templates in KSMUX. It shows methods for loading templates from local directories or embedded file systems, adding custom functions (like `strings.ToUpper`) to templates, and rendering a template with dynamic data.
```go
// Load templates
router.LocalTemplates("templates/")
// or
router.EmbededTemplates(embededFS, "templates/")
// Add custom template functions
router.NewTemplateFunc("upper", strings.ToUpper)
// Render template
router.Get("/", func(c *ksmux.Context) {
c.Html("index.html", map[string]any{
"title": "Home",
"user": user,
})
})
```
--------------------------------
### Cross-Language Client Pub/Sub Operations
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/README.md
Illustrates how to connect to the ksmux pub/sub system and perform core operations like subscribing to topics and publishing messages with acknowledgment across Go, JavaScript, Python, and Dart/Flutter clients.
```Go
client, _ := ksps.NewClient(ksps.ClientConnectOptions{
Address: "localhost:9313",
})
// Subscribe
client.Subscribe("events", func(data any, unsub func()) {
fmt.Printf("Got: %v\n", data)
})
// Publish with ACK
ack := client.PublishWithAck("events", "From Go!", 3*time.Second)
response, ok := ack.WaitAny()
```
```JavaScript
// Browser or Node.js
const client = await BusClient.Client.NewClient({
Address: "localhost:9313", // default: window.location.host
Path: "/ws/newPath", // default: /ws/bus
Secure: false // protocol == 'http:' -> false
});
// Subscribe
client.Subscribe("events", (data, unsub) => {
console.log("Received:", data);
});
// Publish with ACK
const ack = client.PublishWithAck("events", "From JS!", 3000);
const responses = await ack.Wait();
```
```Python
import asyncio
from ksps import Client
async def main():
client = await Client.NewClient(Address="localhost:9313")
# Subscribe
await client.Subscribe("events",
lambda data, unsub: print(f"Got: {data}"))
# Publish with ACK
ack = await client.PublishWithAck("events", "From Python!", 3.0)
responses = await ack.Wait()
asyncio.run(main())
```
```Dart
import 'package:ksps_dart/ksps_dart.dart';
void main() async {
final client = await KspsClient.connect(
ClientConnectOptions(
id: 'dart-client',
address: 'localhost:9313',
),
);
// Subscribe
client.subscribe('events', (data, unsub) {
print('Received: $data');
});
// Publish with ACK
final ack = client.publishWithAck(
'events',
{'msg': 'From Dart!'},
Duration(seconds: 3),
);
final responses = await ack.wait();
}
```
--------------------------------
### Configure and Use Distributed Tracing in KSMUX Go
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
This snippet illustrates how to enable and configure distributed tracing in KSMUX, including setting up exporters for Jaeger or Tempo, adding a custom trace handler, applying tracing middleware, and manually creating spans within request handlers. It covers various aspects of integrating OpenTelemetry-compatible tracing into a KSMUX application.
```go
// Enable tracing with default Jaeger endpoint
ksmux.ConfigureExport("", ksmux.ExportTypeJaeger)
// Or use Tempo
ksmux.ConfigureExport(ksmux.DefaultTempoEndpoint, ksmux.ExportTypeTempo)
// Enable tracing with optional custom handler
ksmux.EnableTracing(&CustomTraceHandler{})
// Add tracing middleware to capture all requests
app.Use(ksmux.TracingMiddleware)
// Manual span creation
app.Get("/api", func(c *ksmux.Context) {
// Create a span
span, ctx := ksmux.StartSpan(c.Request.Context(), "operation-name")
defer span.End()
// Add tags
span.SetTag("key", "value")
// Set error if needed
span.SetError(err)
// Set status code
span.SetStatusCode(200)
// Use context for propagation
doWork(ctx)
})
```
--------------------------------
### Configure KSMUX Tracing Behavior in Go
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
These Go snippets demonstrate how to fine-tune KSMUX's tracing behavior by ignoring specific endpoints from tracing and adjusting the maximum number of traces kept in memory. This helps manage resource usage and focus tracing on relevant application paths.
```go
// Add paths to ignore in tracing
ksmux.IgnoreTracingEndpoints("/health", "/metrics")
```
```go
// Set maximum number of traces to keep in memory
ksmux.SetMaxTraces(500) // Keep only the last 500 traces
```
--------------------------------
### KSMUX Server and Cookie Configuration
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
Details how to configure global server settings and cookie behavior in KSMUX. It covers setting HTTP server timeouts (read, write, idle) and various cookie attributes such as `HttpOnly`, `Secure`, `SameSite`, and `Expires` for enhanced security and control.
```go
// Server timeouts
ksmux.READ_TIMEOUT = 10 * time.Second
ksmux.WRITE_TIMEOUT = 10 * time.Second
ksmux.IDLE_TIMEOUT = 30 * time.Second
// Cookie settings
ksmux.COOKIES_HttpOnly = true
ksmux.COOKIES_SECURE = true
ksmux.COOKIES_SameSite = http.SameSiteStrictMode
ksmux.COOKIES_Expires = 24 * time.Hour
```
--------------------------------
### KSPS Dart Client Publishing API
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/dart/README.md
Describes the methods for publishing messages using the KSPS Dart client. This includes basic topic publishing, direct messages to a specific client ID, and messages directed to a remote server address.
```APIDOC
client.publish(String topic, dynamic data): void
- Publishes a message to a specified topic.
- Parameters:
- topic: String - The topic to publish to.
- data: dynamic - The message payload.
client.publishToId(String targetId, dynamic data): void
- Publishes a direct message to a specific client ID or the server.
- Parameters:
- targetId: String - The ID of the target client or 'server'.
- data: dynamic - The message payload.
client.publishToServer(String serverAddress, dynamic data): void
- Publishes a message to a specific remote server address.
- Parameters:
- serverAddress: String - The address of the target server (e.g., 'remote:9313').
- data: dynamic - The message payload.
```
--------------------------------
### KSPS Dart Client Connection and Properties API
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/dart/README.md
Defines the `KspsClient.connect` method and its `ClientConnectOptions` for establishing a connection to the KSPS server, including parameters for client identification, server address, security, WebSocket path, auto-reconnection settings, and various connection lifecycle callbacks. Also includes client properties like `id`, `isConnected`, and the `close` method.
```APIDOC
KspsClient.connect(ClientConnectOptions options)
- Establishes a connection to the KSPS server.
- Parameters:
- options: ClientConnectOptions - Configuration for the connection.
- id: String - Client identifier.
- address: String - Server address (e.g., 'localhost:9313').
- secure: bool - Use WSS (true) instead of WS (false).
- path: String - WebSocket path (e.g., '/ws/bus').
- autorestart: bool - Enable auto-reconnection on disconnect.
- restartEvery: Duration - Interval for auto-reconnection attempts.
- onDataWs: Function(dynamic data) - Callback for all incoming WebSocket messages.
- onId: Function(dynamic data, VoidCallback unsub) - Callback for direct messages to this client ID.
- onClose: Function() - Callback when the connection closes.
KspsClient.id: String
- Returns the client's unique identifier.
KspsClient.isConnected: bool
- Returns true if the client is currently connected to the server.
KspsClient.close(): Future
- Closes the client's connection to the server.
```
--------------------------------
### KSPS Dart Client Subscription API
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/dart/README.md
Details the methods for managing topic subscriptions within the KSPS Dart client. This includes `client.subscribe` to listen for messages on a specific topic and `client.unsubscribe` or the returned `unsub` function to stop receiving messages.
```APIDOC
client.subscribe(String topic, Function(dynamic data, VoidCallback unsubFn) callback): VoidCallback
- Subscribes the client to a specified topic.
- Parameters:
- topic: String - The topic to subscribe to.
- callback: Function - A function called when a message is received on the topic. Provides the message data and an `unsubFn` to unsubscribe from within the callback.
- Returns: VoidCallback - A function that can be called to unsubscribe from the topic.
client.unsubscribe(String topic): void
- Unsubscribes the client from a specified topic.
```
--------------------------------
### Implement Custom Trace Handler for KSMUX Go
Source: https://github.com/kamalshkeir/ksmux/blob/master/Readme.md
This Go code defines a `CustomTraceHandler` struct and implements its `HandleTrace` method. This allows developers to intercept and process trace span information, such as TraceID, SpanID, and operation name, providing a flexible way to integrate with custom logging or monitoring systems.
```go
type CustomTraceHandler struct{}
func (h *CustomTraceHandler) HandleTrace(span *ksmux.Span) {
// Access span information
fmt.Printf("Trace: %s, Span: %s, Operation: %s\n",
span.TraceID(), span.SpanID(), span.Name())
}
```
--------------------------------
### KSPS Dart Client Acknowledgment (ACK) API
Source: https://github.com/kamalshkeir/ksmux/blob/master/ksps/dart/README.md
Documents the methods for handling message acknowledgments in the KSPS Dart client. This includes publishing messages with ACK, waiting for acknowledgments (all or first), checking ACK status, determining completion, canceling ACK waits, and direct messages with ACK.
```APIDOC
client.publishWithAck(String topic, dynamic data, Duration timeout): ClientAck
- Publishes a message to a topic and expects acknowledgments.
- Parameters:
- topic: String - The topic to publish to.
- data: dynamic - The message payload.
- timeout: Duration - The maximum time to wait for acknowledgments.
- Returns: ClientAck - An object to manage and query the acknowledgment process.
client.publishToIdWithAck(String targetId, dynamic data, Duration timeout): ClientAck
- Publishes a direct message to a specific client ID or the server and expects acknowledgments.
- Parameters:
- targetId: String - The ID of the target client or 'server'.
- data: dynamic - The message payload.
- timeout: Duration - The maximum time to wait for acknowledgments.
- Returns: ClientAck - An object to manage and query the acknowledgment process.
ClientAck.wait(): Future