diff options
| author | Onur Gündüz <ogunduz@gmail.com> | 2026-10-08 03:20:26 +0200 |
|---|---|---|
| committer | Onur Gündüz <ogunduz@gmail.com> | 2026-10-08 03:20:26 +0200 |
| commit | 26306ffc42ba2c8ea3332d14f4e3379c7d855e1e (patch) | |
| tree | a8c458dc13bb09e20633d986429b841cbc35fb31 /README.md | |
| parent | d0aa2923afcb73a721d6ea135809d1d6ece250ad (diff) | |
| download | muxer-26306ffc42ba2c8ea3332d14f4e3379c7d855e1e.tar.gz muxer-26306ffc42ba2c8ea3332d14f4e3379c7d855e1e.zip | |
Fix example shutdown and document basic usage
Diffstat (limited to 'README.md')
| -rw-r--r-- | README.md | 79 |
1 files changed, 78 insertions, 1 deletions
@@ -2,7 +2,84 @@ Simple binary messaging protocol with multiplexing support. -[](https://pkg.go.dev/git.onurgunduz.com/muxer) +## Installation + +```sh +go get git.onurgunduz.com/muxer@latest +``` + +## Usage + +Go 1.25 or later is required. The examples below use these imports: + +```go +import ( + "bufio" + "bytes" + "fmt" + "log" + + "git.onurgunduz.com/muxer" +) +``` + +### Writing a message + +Create a writer around a `bufio.Writer`. This example writes to an in-memory buffer: + +```go +var output bytes.Buffer +writer := muxer.NewWriter(bufio.NewWriter(&output)) +message := muxer.NewMessage(42, 3, []byte("hello")) + +if err := writer.WriteMessage(message); err != nil { + log.Fatal(err) +} +``` + +`WriteMessage` flushes the buffer before returning. Pass multiple messages to write a batch. + +### Reading a message + +Create a reader around any `io.Reader`. This reads the message written above: + +```go +reader := muxer.NewReader(&output) +var received muxer.Message + +if err := reader.ReadMessage(&received); err != nil { + log.Fatal(err) +} +fmt.Printf("%d %d %s\n", received.ID, received.Type, received.Data) +``` + +`ReadMessage` returns `io.EOF` when the source ends. The default buffer size is 4096 bytes; use `NewReaderSize` when messages need a larger buffer. + +The returned `Data` slice shares the reader's storage. Process it before the next read, or copy it with `append([]byte(nil), received.Data...)` if it needs to be kept. + +### Using a TCP connection + +For a server listening on `127.0.0.1:4242` that speaks the muxer protocol and replies to each message: + +```go +conn, err := muxer.Dial("tcp", "127.0.0.1:4242") +if err != nil { + log.Fatal(err) +} +defer conn.Close() + +if _, err := conn.Send(muxer.NewMessage(42, 3, []byte("hello"))); err != nil { + log.Fatal(err) +} + +var response muxer.Message +if err := conn.ReadMessage(&response); err != nil { + log.Fatal(err) +} +fmt.Printf("%d %d %s\n", response.ID, response.Type, response.Data) +``` + +`NewConn` wraps an accepted connection or another `io.ReadWriteCloser`. `Send` can write several messages at once and can be called concurrently. Use one reading goroutine per connection; direct `Reader` and `Writer` calls are not safe for concurrent use. ## Message structure |
