bmux

package module
v1.0.13 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2025 License: MIT Imports: 13 Imported by: 0

README

bmux

bmux is a modular TCP multiplexer and routing framework for Go. It provides a declarative interface for handling custom binary protocols using a router/middleware architecture inspired by modern web frameworks.

Features

  • Pluggable Middleware Support – Global, router-level, and route-level middleware chaining
  • Router-Based Dispatching – Organize handlers in routers with isolated configuration
  • Binary Message Routing – Parse and dispatch TCP messages based on custom headers
  • Concurrent Connection Handling – Efficient handling of multiple clients
  • Structured Configuration – Load runtime options via config.Config
  • Zerolog Integration – Consistent and contextual structured logging support

Installation

go get github.com/etwodev/bmux

Basic Usage

import (
	"github.com/etwodev/bmux"
	"github.com/etwodev/bmux/router"
)

// Define your header struct
type MyHeader struct {
	Command int32
}

func (h *MyHeader) ID() int32 {
	return h.Command
}

// Define a simple handler
func HelloHandler() router.HandlerFunc {
	return func(ctx *router.Context) {
		// handle the message
	}
}

func main() {
	s := bmux.New(&MyHeader{})

	// Create router and register routes
	r := router.New("main")
	r.Route(1, HelloHandler()) // ID 1 mapped to HelloHandler
	s.LoadRouter([]router.Router{r})

	// Start server with config.Address() and config.Port()
	if err := s.Start(); err != nil {
		panic(err)
	}
}

Middleware

You can apply middleware at three levels:

  • Global: Applies to all routes
  • Router-Level: Applies to all routes within a router
  • Route-Level: Applies to individual routes
Example: Logging Middleware
logger := log.NewZeroLogger(zerolog.New(os.Stdout).With().Timestamp().Logger())

loggingMiddleware := middleware.NewLoggingMiddleware(logger)
s.LoadMiddleware([]middleware.Middleware{loggingMiddleware})

Inside your route:

if l := ctx.Context.Value(middleware.LoggerCtxKey); l != nil {
    if logger, ok := l.(log.Logger); ok {
        logger.Info().Msg("Processing route")
    }
}

Configuration

bmux reads runtime configuration via the config.Config struct. This supports:

  • Port and address binding
  • Logging level (debug, info, warn, etc.)
  • Timeout durations
  • Keep-alive toggle
  • Graceful shutdown duration
  • Max concurrent connections

Ensure your config.New() call is invoked during startup to initialize values.

Project Structure

bmux/
├── bmux.go      → Core server and lifecycle
├── config/      → Config loading (JSON, env, etc.)
├── log/         → Abstraction over zerolog
├── middleware/  → Middleware primitives
├── parsing/     → TCP envelope and header parsing
├── router/      → Router, route, and context definitions

Example Config File

{
  "port": "9000",
  "address": "0.0.0.0",
  "logLevel": "debug",
  "bufferSize": 1024,
  "maxConnections": 100,
  "readTimeout": 10,
  "writeTimeout": 10,
  "idleTimeout": 30,
  "shutdownTimeout": 15,
  "enableKeepAlive": true,
  "enablePacketLogging": false
}

Contributing

Contributions are welcome! Please:

  1. Fork the repo
  2. Create a feature branch
  3. Write tests if applicable
  4. Submit a PR with a clear description

License

MIT License © 2025 etwodev

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option func(*Server)

Option allows configuring the Server during creation.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server manages TCP connections and dispatches parsed messages to appropriate route handlers defined via the Router interface.

func New

func New(headerPrototype any, opts ...Option) *Server

New returns a new Server instance with a required header prototype and optional settings.

func (*Server) LoadMiddleware

func (s *Server) LoadMiddleware(mws []middleware.Middleware)

LoadMiddleware appends global middleware to be applied to all routes.

func (*Server) LoadRouter

func (s *Server) LoadRouter(routers []router.Router)

LoadRouter appends routers to the server's list, deferring route registration.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown initiates a graceful shutdown, closing the listener and waiting for all active connections.

func (*Server) Start

func (s *Server) Start() error

Start begins accepting connections on the configured TCP address and port.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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