|
5 | 5 | [](https://pkg.go.dev/github.com/floatdrop/demux) |
6 | 6 | [](https://opensource.org/licenses/MIT) |
7 | 7 |
|
| 8 | +`demux` is a lightweight Go package that provides flexible and generic demultiplexing (fan-out) utilities for channels. It allows you to route items from a single input channel to multiple output channels based on dynamic or static keys. |
| 9 | + |
| 10 | +## Features |
| 11 | + |
| 12 | +- **Dynamic Demuxing**: Automatically spawn goroutines for each unique key, with dedicated channels. |
| 13 | +- **Static Demuxing**: Route messages to pre-defined channels based on their keys. |
| 14 | +- **Generic**: Uses Go generics for maximum flexibility. |
| 15 | + |
8 | 16 | ## Installation |
9 | 17 |
|
10 | 18 | ```bash |
11 | 19 | go get github.com/floatdrop/demux |
12 | 20 | ``` |
13 | 21 |
|
| 22 | +## Usage |
| 23 | + |
| 24 | +### Dynamic Demuxing |
| 25 | + |
| 26 | +`Dynamic` demuxes messages from an input channel to a dynamically created set of output channels, one per key. Each unique key launches a dedicated goroutine running `consumeFunc`. |
| 27 | + |
| 28 | +```golang |
| 29 | +demux.Dynamic(input, func(msg MyType) string { |
| 30 | + return msg.UserID // or any key |
| 31 | +}, func(key string, ch <-chan MyType) { |
| 32 | + for msg := range ch { // start consuming messages with same UserID |
| 33 | + fmt.Printf("Consumer for %s got: %+v\n", key, msg) |
| 34 | + } |
| 35 | +}) |
| 36 | +``` |
| 37 | + |
| 38 | +### Static Demuxing |
| 39 | + |
| 40 | +`Static` demuxes messages based on a key and routes them to pre-defined channels in a map. |
| 41 | + |
| 42 | +```golang |
| 43 | +channels := map[string]chan MyType{ |
| 44 | + "alpha": make(chan MyType), |
| 45 | + "beta": make(chan MyType), |
| 46 | +} |
| 47 | + |
| 48 | +go demux.Static(input, func(msg MyType) string { |
| 49 | + return msg.Group |
| 50 | +}, channels) |
| 51 | +``` |
| 52 | + |
14 | 53 | ## Contributing |
15 | 54 |
|
16 | 55 | Contributions are welcome! Please feel free to submit a Pull Request. |
|
0 commit comments