{"id":44647865,"url":"https://github.com/whitekid/goxp","last_synced_at":"2026-02-14T20:18:28.290Z","repository":{"id":40471761,"uuid":"152032801","full_name":"whitekid/goxp","owner":"whitekid","description":"go utility functions for simple life","archived":false,"fork":false,"pushed_at":"2025-10-02T16:42:31.000Z","size":558,"stargazers_count":1,"open_issues_count":3,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-10-02T17:42:42.161Z","etag":null,"topics":["go","golang","library"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/whitekid.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":"2018-10-08T06:59:54.000Z","updated_at":"2025-10-02T16:42:36.000Z","dependencies_parsed_at":"2023-02-17T03:01:10.028Z","dependency_job_id":"fed08491-de0a-4fb4-ba9f-ef064814cbb7","html_url":"https://github.com/whitekid/goxp","commit_stats":null,"previous_names":["whitekid/go-utils"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/whitekid/goxp","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/whitekid%2Fgoxp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/whitekid%2Fgoxp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/whitekid%2Fgoxp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/whitekid%2Fgoxp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/whitekid","download_url":"https://codeload.github.com/whitekid/goxp/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/whitekid%2Fgoxp/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29455317,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-14T15:52:44.973Z","status":"ssl_error","status_checked_at":"2026-02-14T15:52:11.208Z","response_time":53,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"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":["go","golang","library"],"created_at":"2026-02-14T20:18:25.335Z","updated_at":"2026-02-14T20:18:28.281Z","avatar_url":"https://github.com/whitekid.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# goxp - Go Utility Function Collection\n\n[![Go](https://github.com/whitekid/goxp/actions/workflows/go.yml/badge.svg)](https://github.com/whitekid/goxp/actions/workflows/go.yml)\n[![Go Report Card](https://goreportcard.com/badge/github.com/whitekid/goxp)](https://goreportcard.com/report/github.com/whitekid/goxp)\n\nA comprehensive collection of Go utility functions and packages designed for modern Go development (Go 1.24+). Features performance-optimized implementations, type-safe generics, and comprehensive testing.\n\nFor detailed usage examples, please refer to the test cases in each package.\n\n## Core Functionality\n\n### Goroutines \u0026 Concurrency\n\n|                      |                                                            |\n| -------------------- | ---------------------------------------------------------- |\n| `DoWithWorker()`     | execute function with worker pool (context-aware)          |\n| `Every()`            | run function at regular intervals (context-aware)          |\n| `After()`            | run function after delay (context-aware)                   |\n| `Async()`,`Async2()` | run function asynchronously and receive result via channel |\n\n```go\n// Worker pool with optimized performance\nerr := DoWithWorker(ctx, 4, func(ctx context.Context, workerID int) error {\n    fmt.Printf(\"Worker %d processing\\n\", workerID)\n    return processJob(ctx)\n})\n\n// Periodic execution\nerr := Every(ctx, 5*time.Second, true, func(ctx context.Context) {\n    updateMetrics(ctx)\n})\n\n// Asynchronous execution\nresultCh := Async(ctx, func(ctx context.Context) string {\n    return fetchData(ctx)\n})\nresult := \u003c-resultCh\n```\n\n### Data Encoding/Decoding (Type-Safe Generics)\n\n|                     |                                    |\n| ------------------- | ---------------------------------- |\n| `ReadJSON[T]`       | decode JSON to type with generics  |\n| `WriteJSON[T]`      | encode type to JSON writer         |\n| `MustMarshalJson()` | marshal JSON or panic              |\n| `ReadXML[T]`        | decode XML to type with generics   |\n| `WriteXML[T]`       | encode type to XML writer          |\n| `ReadYAML[T]`       | decode YAML to type with generics  |\n| `WriteYAML[T]`      | encode type to YAML writer         |\n\n```go\n// Type-safe JSON operations\nvar config Config\nerr := ReadJSON[Config](reader, \u0026config)\n\n// Must marshal - panic on error\npayload := MustMarshalJson(data)\n\n// Direct type inference\nusers, err := ReadJSON[[]User](reader)\n```\n\n### Utility Functions\n\n|                   |                                |\n| ----------------- | ------------------------------ |\n| `SetBits()`       | set bits in integer            |\n| `ClearBits()`     | clear bits in integer          |\n| `IsContextDone()` | return true if context is done |\n| `WithTimeout()`   | run fn() with timeout context  |\n| `Must(error)`     | panic if error not nil         |\n| `NewPool[T]()`    | `sync.Pool` with generics      |\n| `Abs[T]()`        | absolute value with generics   |\n| `Timer()`         | measure execution time         |\n\n```go\n// Generic pool for any type\npool := NewPool[*bytes.Buffer](func() *bytes.Buffer {\n    return \u0026bytes.Buffer{}\n})\n\n// Execution timing\ndefer Timer(\"operation\")()\n// Output: time takes 123.45ms: operation\n```\n\n### String Parsing with Defaults\n\n|                   |                                          |\n| ----------------- | ---------------------------------------- |\n| `AtoiDef[T]()`    | `strconv.Atoi()` with default value      |\n| `ParseBoolDef()`  | `strconv.ParseBool()` with default value |\n| `ParseIntDef[T]()` | `strconv.ParseInt()` with default value  |\n\n```go\n// Safe parsing with defaults\nport := AtoiDef(os.Getenv(\"PORT\"), 8080)           // defaults to 8080\ntimeout := ParseIntDef[int64](cfg.Timeout, 30)     // defaults to 30\ndebug := ParseBoolDef(os.Getenv(\"DEBUG\"), false)   // defaults to false\n```\n\n### Time Parsing and Formatting\n\n|                   |                                             |\n| ----------------- | ------------------------------------------- |\n| `ParseDateTime()` | parse string to time for well known layouts |\n| `TimeWithLayout`  | `time.Time` with layouts                    |\n| `RFC1123ZTime`    | `Mon, 02 Jan 2006 15:04:05 -0700`           |\n| `RFC3339Time`     | `2006-01-02T15:04:05Z07:00`                 |\n\n```go\n// Smart time parsing\nt, err := ParseDateTime(\"2023-12-25T10:30:00Z\")     // Auto-detects format\nrfc3339 := RFC3339Time(time.Now())                  // Formats as RFC3339\nrfc1123 := RFC1123ZTime(time.Now())                 // Formats as RFC1123Z\n```\n\n### Shell Execution\n\n**Security Warning**: Be careful with shell command execution. Always validate and sanitize inputs to prevent command injection attacks.\n\n#### `Exec()` - simple run command\n\n```go\n// Run command and output to stdin/stdout\nexc := Exec(\"ls\", \"-al\")\nerr := exc.Do(context.Background())\nrequire.NoError(t, err)\n\n// Run command and get output\nexc := Exec(\"ls\", \"-al\")\noutput, err := exc.Output(context.Background())\nrequire.NoError(t, err)\nrequire.Contains(t, string(output), \"README.md\")\n```\n\n#### `Pipe()` - run command with pipe\n\n### Conditional Execution\n\n#### `If()`, `Else()`, `IfThen()` - functional conditionals\n\n```go\nIfThen(true, func() { fmt.Printf(\"true\\n\") })\n// Output: true\n\nIfThen(condition, \n    func() { fmt.Printf(\"true\\n\") }, \n    func() { fmt.Printf(\"false\\n\") })\n\n// Multiple else conditions supported\nIfThen(false, \n    func() { fmt.Printf(\"condition1\\n\") }, \n    func() { fmt.Printf(\"condition2\\n\") }, \n    func() { fmt.Printf(\"default\\n\") })\n```\n\n[Go Playground](https://go.dev/play/p/wNadBmhNYR-)\n\n#### `Ternary()`, `TernaryF()`, `TernaryCF()` - ternary operations\n\n```go\n// Simple ternary\nresult := Ternary(condition, \"yes\", \"no\")\n\n// Function-based ternary (lazy evaluation)\nresult := TernaryF(condition, \n    func() string { return expensiveTrue() }, \n    func() string { return expensiveFalse() })\n```\n\n### Random String/Byte Generation\n\n**Security**: Uses cryptographically secure random generation with input validation.\n\n#### `RandomByte()` - generate random bytes\n\n```go\nb := RandomByte(10)\n// hex.EncodeToString(b) = \"4d46ef2f87b8191daf58\"\n```\n\n#### `RandomString()`, `RandomStringWith()` - generate random strings\n\n```go\ns := RandomString(10)\n// s = \"$c\u0026I$#LR3Y\"\n\n// Custom character set with validation\ns := RandomStringWith(10, []rune(\"abcdefg\"))\n// s = \"bbffedabda\"\n\n// Size limits enforced for security (max 1MB)\ns := RandomStringWith(1000, []rune(\"0123456789\"))\n```\n\n### Performance Measurement\n\n```go\nfunc doSomething() {\n    defer Timer(\"doSomething()\")()\n    time.Sleep(500 * time.Millisecond)\n}\n\ndoSomething()\n// Output: time takes 500.505063ms: doSomething()\n```\n\n[Go Playground](https://go.dev/play/p/Wcj2Hw5CLL6)\n\n### Tuple Support\n\n|                    |                              |\n| ------------------ | ---------------------------- |\n| `Tuple2`, `Tuple3` | `Pack()` and `Unpack()`      |\n| `T2`,`T3`          | construct tuple with element |\n\n```go\n// Create and unpack tuples\ntuple := T2(\"hello\", 42)\nstr, num := tuple.Unpack()\n\n// Multi-return functions\nfunc getData() (string, int, error) {\n    return \"data\", 123, nil\n}\nresult := T3(getData())\n```\n\n## Sub-packages\n\n### High-Performance HTTP Client\n- **[requests](requests)** - Simple HTTP client with connection pooling and buffer optimization\n  ```go\n  resp, err := requests.Get(\"https://api.example.com\").\n      Header(\"Authorization\", \"Bearer token\").\n      JSON(payload).\n      Do(ctx)\n  ```\n\n### Data Structure Extensions\n- **[slicex](slicex)** - Performance-optimized slice operations with generics and `iter.Seq` support\n- **[mapx](mapx)** - Map extensions with functional operations and optimized sampling\n- **[sets](sets)** - Set data structure implementation with `SetNX()` support\n- **[chanx](chanx)** - Channel extensions and utilities\n\n### Functional Programming\n- **[fx](fx)** - Experimental functional programming with `iter.Seq` (Go 1.24+)\n- **[fx/gen](fx/gen)** - Generator functions and utilities\n- **[iterx](iterx)** - Iterator extensions and helper functions\n\n### Security \u0026 Crypto\n- **[cryptox](cryptox)** - Encryption/decryption functions (DES deprecated, use AES)\n- **[x509x](x509x)** - X.509 certificate utilities\n\n### Development Tools\n- **[log](log)** - Simple structured logging powered by Zap\n- **[errors](errors)** - Errors with stack traces and rich formatting\n- **[retry](retry)** - Retry mechanisms with backoff strategies\n- **[services](services)** - Simple service framework with lifecycle management\n\n### Testing \u0026 Validation\n- **[testx](testx)** - Unit test utility functions\n- **[fixtures](fixtures)** - Test fixture management (env vars, files)\n- **[httptest](httptest)** - HTTP test server utilities\n- **[validate](validate)** - Struct validation made easy\n\n### CLI \u0026 Configuration\n- **[cobrax](cobrax)** - Cobra command utilities with simplified command creation\n  ```go\n  // Create root command\n  rootCmd := cobrax.Add(nil, \u0026cobra.Command{Use: \"app\"}, nil)\n  // Add subcommand with configuration\n  cobrax.Add(rootCmd, \u0026cobra.Command{Use: \"sub\"}, func(cmd *cobra.Command) {\n      cmd.Flags().StringP(\"name\", \"n\", \"\", \"name flag\")\n  })\n  ```\n- **[flags](flags)** - Command-line flag management\n- **[slug](slug)** - UUID to slug conversion\n\n## Performance Optimizations\n\nRecent performance improvements include:\n\n- **HTTP Client**: Connection pooling, buffer reuse, optimized timeouts\n- **Sampling Operations**: 100x performance improvement using `math/rand` instead of `crypto/rand`\n- **Algorithm Efficiency**: Fisher-Yates shuffle for O(n) complexity\n- **Memory Management**: Buffer pooling and reduced allocations\n- **Type Safety**: Extensive use of Go generics for zero-cost abstractions\n\n## Security Considerations\n\n**Security Features:**\n- Input validation and size limits in random string generation\n- Secure logging practices (no sensitive data in logs)  \n- Deprecation warnings for insecure cryptographic functions\n- Command injection prevention guidance\n\n**Security Warnings:**\n- Always validate shell command inputs\n- DES encryption is deprecated - use AES instead\n- Be cautious with command execution functions\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwhitekid%2Fgoxp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwhitekid%2Fgoxp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwhitekid%2Fgoxp/lists"}