Skip to content

Commit

Permalink
Yay, it.Might arrived
Browse files Browse the repository at this point in the history
  • Loading branch information
theHamdiz committed Feb 3, 2025
1 parent d418ea7 commit 60bda5f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,40 @@ maybeConnect := it.Could(func() (*sql.DB, error) {
db := maybeConnect() // First call actually does the work
alsoDb := maybeConnect() // Returns same result, wasn't worth trying again anyway

if value, ok := it.Might(maybeThisWorks); ok {
// Nice, we got something
} else {
// No biggie, we weren't counting on it anyway
}

// The "cover your tracks" strategy
err := it.WrapError(dbErr, "database had an existential crisis",
map[string]any{"attempt": 42, "mood": "gothic"})
```

### SafeGo - Panic-Proof Goroutines

Because letting goroutines die alone in the dark is just cruel.

```go
import "github.com/theHamdiz/it"

// Fire and forget (but not really)
it.SafeGo(func() {
DoSomethingDangerous() // We'll catch you if you fall
})

// For the context-aware crowd
it.SafeGoWithContext(ctx, func(ctx context.Context) {
ResponsiblyDangerous(ctx) // Safety first, but make it contextual
})
```

Includes automatic panic recovery and proper context propagation. Perfect for when you want to live dangerously but with a safety net.

Now go forth and spawn goroutines without fear of them taking your program down with them.


### Logging (Now with proper prefixes)

```go
Expand Down
12 changes: 12 additions & 0 deletions it.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,18 @@ func Could[T any](operation func() (T, error)) func() T {
}
}

// Might is for when success is optional but you'd like to know about it
// Returns (value, true) if it worked, (zero, false) if it didn't
func Might[T any](operation func() (T, error)) (T, bool) {
result, err := operation()
if err != nil {
logger.DefaultLogger().Debug(fmt.Sprintf("it didn't work out: %v", err))
var zero T
return zero, false
}
return result, true
}

// WrapError wraps an error with a custom message and additional metadata.
// If the original error is nil, it simply returns nil.
func WrapError(err error, message string, metadata map[string]any) error {
Expand Down

0 comments on commit 60bda5f

Please sign in to comment.