safego

package module
v0.0.0-...-5684faf Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2025 License: MIT Imports: 2 Imported by: 0

README

safego

SafeGo is a simple Go package that provides a basic safety template for goroutine function execution with panic recovery and context support.

Installation

go get github.com/sxtsr/safego

Features

  • Panic recovery in goroutines
  • Context-aware goroutine execution
  • Simple and lightweight implementation

Usage Examples

Basic Usage
package main

import (
    "fmt"
    "github.com/sxtsr/safego"
)

func main() {
    // Example of safe goroutine execution
    safego.Go(func() {
        fmt.Println("Executing safely in goroutine")
        
        // Even if panic occurs, it will be recovered and logged
        panic("test panic")
    })
}
With Context
package main

import (
    "context"
    "fmt"
    "github.com/sxtsr/safego"
    "time"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    safego.GoContext(ctx, func() {
        fmt.Println("Executing with context")
        // Will not execute if context is canceled
    })
}
Multiple Goroutines
package main

import (
    "fmt"
    "github.com/sxtsr/safego"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    
    for i := 0; i < 5; i++ {
        wg.Add(1)
        i := i
        
        safego.Go(func() {
            defer wg.Done()
            fmt.Printf("Processing item %d\n", i)
        })
    }
    
    wg.Wait()
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Go

func Go(fn func())

Go executes the provided function fn in a goroutine with safety features. It provides the following safety mechanisms:

`Panic recovery` to prevent application crashes
`Parameters`:
    'fn': The function to be executed in the goroutine

Any panics during execution will be recovered and logged.

func GoContext

func GoContext(ctx context.Context, fn func())

GoContext executes the provided function fn in a goroutine with safety features. It provides the following safety mechanisms:

`Panic recovery` to prevent application crashes
`Context` checking for proper cancellation support
`Parameters`:
    'ctx': Context for cancellation control
    'fn': The function to be executed in the goroutine

The function will not execute if the context is already canceled. Any panics during execution will be recovered and logged.

Types

This section is empty.

Jump to

Keyboard shortcuts

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