{"id":32532691,"url":"https://github.com/yosebyte/x","last_synced_at":"2025-10-28T12:55:54.965Z","repository":{"id":269498566,"uuid":"907604799","full_name":"yosebyte/x","owner":"yosebyte","description":"Shared Resources","archived":false,"fork":false,"pushed_at":"2025-09-17T03:20:48.000Z","size":12702,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-17T05:36:14.534Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Shell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yosebyte.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-12-24T01:22:41.000Z","updated_at":"2025-09-17T03:20:52.000Z","dependencies_parsed_at":"2025-01-22T15:28:42.763Z","dependency_job_id":"6a48f723-28a5-46d6-a408-ff2d863dc408","html_url":"https://github.com/yosebyte/x","commit_stats":null,"previous_names":["yosebyte/x"],"tags_count":31,"template":false,"template_full_name":null,"purl":"pkg:github/yosebyte/x","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yosebyte%2Fx","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yosebyte%2Fx/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yosebyte%2Fx/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yosebyte%2Fx/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yosebyte","download_url":"https://codeload.github.com/yosebyte/x/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yosebyte%2Fx/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":281441022,"owners_count":26501758,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-28T02:00:06.022Z","response_time":60,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-10-28T12:55:54.032Z","updated_at":"2025-10-28T12:55:54.956Z","avatar_url":"https://github.com/yosebyte.png","language":"Shell","funding_links":[],"categories":[],"sub_categories":[],"readme":"# yosebyte/x\n\nA comprehensive utility library for Go applications that provides robust connection management, TLS configuration generation, and structured logging. This library is designed to simplify common networking and operational tasks in Go applications with a focus on reliability and performance.\n\n[![Go Reference](https://pkg.go.dev/badge/github.com/yosebyte/x.svg)](https://pkg.go.dev/github.com/yosebyte/x)\n[![Go Report Card](https://goreportcard.com/badge/github.com/yosebyte/x)](https://goreportcard.com/report/github.com/yosebyte/x)\n\n## Table of Contents\n\n- [Installation](#installation)\n- [Packages](#packages)\n  - [conn - Connection Pooling and I/O Utilities](#conn---connection-pooling-and-io-utilities)\n  - [tls - TLS Configuration Generator](#tls---tls-configuration-generator)\n  - [log - Structured Logging](#log---structured-logging)\n- [Performance Considerations](#performance-considerations)\n- [Thread Safety](#thread-safety)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Installation\n\n```bash\ngo get github.com/yosebyte/x\n```\n\nFor a specific version:\n\n```bash\ngo get github.com/yosebyte/x\n```\n\nTo update to the latest version:\n\n```bash\ngo get -u github.com/yosebyte/x\n```\n\n## Packages\n\n### conn - Connection Pooling and I/O Utilities\n\nThe `conn` package provides sophisticated connection pooling mechanisms and data exchange utilities for managing network connections efficiently.\n\n```go\nimport \"github.com/yosebyte/x/conn\"\n```\n\n#### Connection Pools\n\nThree specialized types of connection pools are available, each designed for different use cases:\n\n##### BrokerPool\n\nMaintains a dynamic pool of connections for broker applications, with automatic scaling and connection health checking.\n\n```go\n// Create a broker pool with min/max capacity and connection interval management\npool := conn.NewBrokerPool(\n    5,                  // minimum capacity\n    20,                 // maximum capacity\n    time.Second,        // minimum interval\n    time.Minute,        // maximum interval\n    func() (net.Conn, error) {\n        return net.Dial(\"tcp\", \"example.com:80\")\n    },\n)\n\n// Start the connection manager in a goroutine\ngo pool.BrokerManager()\n\n// Get a connection from the pool\nid, netConn := pool.BrokerGet()\nif netConn == nil {\n    // Handle connection error\n    fmt.Println(\"Connection error:\", id)\n    return\n}\n\n// Use the connection\n// ...\n\n// Close the pool when done with all operations\ndefer pool.Close()\n\n// Check the current active connections and capacity\nfmt.Printf(\"Active connections: %d, Capacity: %d\\n\", pool.Active(), pool.Capacity())\n```\n\n##### ClientPool\n\nManages outbound client connections with automatic scaling based on usage patterns and TLS support.\n\n```go\n// Create a client pool\nclientPool := conn.NewClientPool(\n    3,                  // minimum capacity\n    10,                 // maximum capacity\n    time.Second,        // minimum interval\n    time.Minute,        // maximum interval\n    \"1\",                // TLS code: \"0\" = no TLS, \"1\" = insecure TLS, \"2\" = secure TLS with hostname verification\n    \"example.com\",      // hostname for verification (used with TLS code \"2\")\n    func() (net.Conn, error) {\n        return net.Dial(\"tcp\", \"api.example.com:443\")\n    },\n)\n\n// Start the client manager\ngo clientPool.ClientManager()\n\n// Retrieve a specific connection by ID\nconn := clientPool.ClientGet(\"connection-id\")\n```\n\n##### ServerPool\n\nHandles incoming server connections with built-in acceptance limiting and TLS support.\n\n```go\n// Create a TCP listener\nlistener, err := net.Listen(\"tcp\", \":8080\")\nif err != nil {\n    log.Fatal(err)\n}\n\n// Create a server pool with TLS support\nserverPool := conn.NewServerPool(\n    tlsConfig,          // TLS configuration (can be nil for non-TLS)\n    listener,           // network listener\n)\n\n// Start the server manager\ngo serverPool.ServerManager()\n\n// Get a new connection with its ID\nid, conn := serverPool.ServerGet()\n```\n\n#### Connection Pool Management\n\nAll pool types offer methods to monitor and control the connection lifecycle:\n\n```go\n// Get the current number of active connections\nactiveCount := pool.Active()\n\n// Get the current capacity setting\ncapacity := pool.Capacity()\n\n// Get the current interval between connection attempts (BrokerPool only)\ninterval := pool.Interval()\n\n// Check if the pool is ready and initialized\nisReady := pool.Ready()\n\n// Remove all connections in the pool but keep the pool active\npool.Flush()\n\n// Close all connections in the pool and stop the manager\npool.Close()\n```\n\n#### Data Exchange\n\nThe package includes a highly efficient bidirectional data exchange function that handles proper connection closure and error propagation:\n\n```go\n// Exchange data between two connections (e.g., proxy implementation)\nbytesClient2Server, bytesServer2Client, err := conn.DataExchange(clientConn, serverConn)\n\nif err != nil \u0026\u0026 err != io.EOF {\n    fmt.Printf(\"Data exchange error: %v\\n\", err)\n}\n\nfmt.Printf(\"Transferred %d bytes from client to server\\n\", bytesClient2Server)\nfmt.Printf(\"Transferred %d bytes from server to client\\n\", bytesServer2Client)\n```\n\n### tls - TLS Configuration Generator\n\nThe `tls` package simplifies the creation of TLS configurations with self-signed certificates for development, testing, or internal services.\n\n```go\nimport \"github.com/yosebyte/x/tls\"\n```\n\n#### Generate Self-Signed TLS Configuration\n\nCreate a TLS configuration with a dynamically generated self-signed certificate:\n\n```go\n// Generate a TLS config with organization name \"my-application\"\ntlsConfig, err := tls.GenerateTLSConfig(\"my-application\")\nif err != nil {\n    log.Fatalf(\"Failed to generate TLS config: %v\", err)\n}\n\n// Use the config with a TLS listener\nlistener, err := tls.Listen(\"tcp\", \":443\", tlsConfig)\nif err != nil {\n    log.Fatalf(\"Failed to create TLS listener: %v\", err)\n}\n\n// Accept TLS connections\nfor {\n    conn, err := listener.Accept()\n    if err != nil {\n        log.Printf(\"Accept error: %v\", err)\n        continue\n    }\n    \n    go handleConnection(conn)\n}\n```\n\n#### Key Certificate Details\n\nThe generated certificate:\n- Uses ECDSA keys with P256 curve\n- Is valid 1 year from creation\n- Includes the provided organization name\n- Has appropriate key usages for server authentication\n\nThis is ideal for:\n- Development environments\n- Internal services\n- Testing TLS implementations\n- Situations where obtaining a public CA certificate is not practical\n\n### log - Structured Logging\n\nThe `log` package provides a simple yet powerful logging system with level-based filtering, color-coded output, and formatting support.\n\n```go\nimport \"github.com/yosebyte/x/log\"\n```\n\n#### Creating a Logger\n\n```go\n// Create a new logger with minimum log level and color enabled\nlogger := log.NewLogger(log.Info, true)\n```\n\n#### Log Levels\n\nThe package supports five standard log levels with corresponding methods:\n\n```go\n// Available log levels in increasing order of severity\nlogger.Debug(\"Database query completed in %d ms\", queryTime) // Detailed debugging information\nlogger.Info(\"User %s logged in successfully\", username)      // Normal operational messages\nlogger.Warn(\"API rate limit at 80%% capacity\")               // Warning conditions\nlogger.Error(\"Failed to connect to database: %v\", err)       // Error conditions\nlogger.Fatal(\"System shutdown due to critical failure\")      // Critical errors\n```\n\n#### Dynamic Configuration\n\nLog settings can be adjusted at runtime:\n\n```go\n// Change minimum log level dynamically\nlogger.SetLogLevel(log.Debug)  // Show all logs including debug\nlogger.SetLogLevel(log.Error)  // Show only error and fatal logs\n\n// Get current log level\ncurrentLevel := logger.GetLogLevel()\n\n// Toggle colored output\nlogger.EnableColor(false)  // Disable colors (useful for log files)\nlogger.EnableColor(true)   // Enable colors (better for console)\n```\n\n#### Standard Library Integration\n\nThe logger can be adapted to work with packages expecting the standard library logger:\n\n```go\n// Get a standard library logger adapter\nstdLogger := logger.StdLogger()\n\n// Use with standard library interfaces\nhttp.DefaultClient.Transport = \u0026http.Transport{\n    DialContext: (\u0026net.Dialer{\n        Timeout:   30 * time.Second,\n        KeepAlive: 30 * time.Second,\n    }).DialContext,\n    MaxIdleConns:          100,\n    IdleConnTimeout:       90 * time.Second,\n    TLSHandshakeTimeout:   10 * time.Second,\n    ExpectContinueTimeout: 1 * time.Second,\n}\nhttp.DefaultClient.Transport.(*http.Transport).DisableCompression = true\n\n// Messages logged through the standard logger will appear in your custom logger\n// with the \"Internal:\" prefix at Debug level\n```\n\n#### Color-Coded Output\n\nWhen color is enabled, log levels are displayed with distinctive colors:\n- DEBUG: Blue\n- INFO: Green\n- WARN: Yellow\n- ERROR: Red\n- FATAL: Purple\n\n## Performance Considerations\n\n- Connection pools automatically adjust capacity based on usage patterns\n- TLS certificate generation is CPU-intensive and should be done during startup\n- Logging has minimal overhead, especially when higher log levels are filtered out\n\n## Thread Safety\n\nAll components in this library are designed to be thread-safe and can be safely used from multiple goroutines.\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## License\n\n[MIT License](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyosebyte%2Fx","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyosebyte%2Fx","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyosebyte%2Fx/lists"}