funk

package module
v2.0.0-alpha.17 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2025 License: MIT Imports: 4 Imported by: 0

README

Funk

Funk is a comprehensive Go utility library that provides enhanced error handling, result types, feature flags, and various helper functions to simplify Go development.

Features

🚀 Enhanced Error Handling
  • Rich error wrapping with stack traces
  • Error codes compatible with gRPC status codes
  • Detailed error context and metadata
  • Panic recovery mechanisms
📦 Result Types
  • Functional programming-inspired Result and Error types
  • Safe error handling without explicit nil checks
  • Comprehensive API for mapping, filtering, and transforming results
  • Async support with Future types
🎛️ Feature Flags
  • Dynamic configuration at runtime
  • Environment variable integration
  • CLI flag generation
  • Type-safe feature access
📝 Configuration Management
  • YAML-based configuration with environment variable substitution
  • Support for configuration merging and extension
  • Expression engine for dynamic configuration values (similar to GitHub Actions workflow syntax)
  • Hot-reloading capabilities
🪵 Structured Logging
  • High-performance logging based on zerolog
  • Context-aware logging with automatic field injection
  • Error detail capture with stack traces
  • Modular logger support with namespacing
🌍 Environment Management
  • Normalized environment variable access
  • Type-safe environment variable retrieval
  • .env file loading and parsing
  • Environment variable expansion
📚 Stack Trace Analysis
  • Runtime stack trace capture
  • Caller identification and metadata extraction
  • Performance-optimized stack operations
  • Deep Go runtime integration
🔧 Utility Functions
  • Generic helper functions for slices, maps, and comparisons
  • Assertion utilities
  • Path and file utilities
  • String and formatting helpers

Installation

go get github.com/pubgo/funk/v2

Quick Start

Error Handling
import "github.com/pubgo/funk/v2/errors"

err := errors.New("something went wrong", errors.Tags{"component": "database"})
err = errors.Wrap(err, "failed to connect")
errors.DebugPrint(err)
Result Types
import "github.com/pubgo/funk/v2/result"

// Create a successful result
res := result.OK(42)

// Create a failed result
errRes := result.Fail[int](errors.New("calculation failed"))

// Safely unwrap values
if value, ok := res.TryUnwrap(); ok {
    fmt.Printf("Got value: %d\n", value)
}

// Chain operations
result := result.OK(10).
    Map(func(x int) int { return x * 2 }).
    FlatMap(func(x int) result.Result[int] {
        if x > 0 {
            return result.OK(x + 1)
        }
        return result.Fail[int](errors.New("negative value"))
    })
Feature Flags
import "github.com/pubgo/funk/v2/features"

// Define a feature flag
var debugMode = features.Bool("debug", false, "Enable debug mode")

// Use the feature flag
if debugMode.Value() {
    log.Println("Debug mode enabled")
}
Configuration
import "github.com/pubgo/funk/v2/config"

type Config struct {
    Server struct {
        Host string `yaml:"host"`
        Port int    `yaml:"port"`
    } `yaml:"server"`
}

cfg := config.Load[Config]()
fmt.Printf("Server will run on %s:%d\n", cfg.T.Server.Host, cfg.T.Server.Port)
Logging
import "github.com/pubgo/funk/v2/log"

logger := log.GetLogger("myapp")
logger.Info().Msg("Application started")
logger.Err(someError).Msg("An error occurred")
Environment Variables
import "github.com/pubgo/funk/v2/env"

// Get environment variable with fallback
host := env.GetOr("SERVER_HOST", "localhost")

// Type-safe environment variable access
port := env.GetInt("SERVER_PORT", "PORT")
debug := env.GetBool("DEBUG")
Stack Trace Analysis
import "github.com/pubgo/funk/v2/stack"

// Capture current stack trace
frames := stack.Trace()

// Get caller information
caller := stack.Caller(0)
fmt.Printf("Called from: %s:%d\n", caller.File, caller.Line)

Modules

  • errors: Enhanced error handling with wrapping, stack traces, and metadata
  • result: Functional Result and Error types for safer error handling
  • features: Feature flag system for runtime configuration
  • assert: Assertion utilities for testing and validation
  • config: Configuration management with multiple sources
  • log: Enhanced logging capabilities
  • env: Environment variable management
  • stack: Stack trace analysis and caller identification

Documentation

For detailed documentation, please visit:

Contributing

Contributions are welcome! Please read our contributing guidelines before submitting pull requests.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendOf

func AppendOf[T any](v T, vv ...T) []T

func Call

func Call[T any](fn func() T) T

func Contains

func Contains[T comparable](vs []T, e T) bool

Contains returns whether `vs` contains the element `e` by comparing vs[i] == e.

func Delete

func Delete[T comparable](set []T, value T) []T

Delete the first occurrence of a type from a set.

func DeleteAll

func DeleteAll[T comparable](set []T, value T) []T

DeleteAll occurrences from a set.

func DoFunc

func DoFunc[T any](fn func() T) T

func DoSelf

func DoSelf[T any](t T, fn func(t T)) T

func Equals

func Equals[T comparable](a, b T) bool

Equals wraps the '==' operator for comparable types.

func Filter

func Filter[T any](set []T, checkTrue func(T) bool) []T

Filter iterates over `set` and gets the values that match `criteria`.

Filter will return a new allocated slice.

func FromPtr

func FromPtr[T any](v *T) (r T)

func IsNil

func IsNil(err any) bool

func Last

func Last[T any](args []T) (t T)

func ListOf

func ListOf[T any](args ...T) []T

func Map

func Map[T, V any](data []T, handle func(d T) V) []V

func Max

func Max[T cmp.Ordered](a, b T) (r T)

Max returns the max of the 2 passed values.

func Min

func Min[T cmp.Ordered](a, b T) (r T)

Min returns the min of the 2 passed values.

func Nil

func Nil[T any]() (t *T)

func ReleaseVersion

func ReleaseVersion() string

func Ternary

func Ternary[T any](ok bool, a, b T) T

func TernaryFn

func TernaryFn[T any](ok bool, a, b func() T) T

func ToPtr

func ToPtr[T any](v T) *T

func Zero

func Zero[T any]() (ret T)

Types

type Ctx

type Ctx[T any] map[string]T

func (Ctx[T]) ToTuple

func (c Ctx[T]) ToTuple() Tuple[T]

type KV

type KV[T any] struct {
	K string `json:"key"`
	V T      `json:"value"`
}

type List

type List[T any] []T

type Tuple

type Tuple[T any] []KV[T]

func (Tuple[T]) ToCtx

func (t Tuple[T]) ToCtx() Ctx[T]

type Void

type Void struct{}

func Init

func Init(fn func()) Void

Directories

Path Synopsis
cmds
ent
testmain command
component
errcode
Package errcode provides error code handling with gRPC compatibility.
Package errcode provides error code handling with gRPC compatibility.
example command
main.go
main.go
graph
dag
internal
example/errors command
example/js command
example/log command
log
platform
proto
testcodepb
Code generated by protoc-gen-deepcopy.
Code generated by protoc-gen-deepcopy.
Package syncutil Package buffer provides an implementation of an unbounded buffer.
Package syncutil Package buffer provides an implementation of an unbounded buffer.

Jump to

Keyboard shortcuts

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