Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

394 Commits

Repository files navigation

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

🔀 Connection Multiplexing

  • Serve gRPC/HTTP/1/HTTP/2 on the same port (connection sniffing)
  • Package: connmux (see connmux/README.md)

Installation

go get github.com/pubgo/funk/v2

Quick Start

Error Handling

import"github.com/pubgo/funk/v2/errors"err:=errors.New("connection failed", errors.Tags{"component": "database"})
err=errors.Wrap(err, "initialize service")
fmt.Println(err.Error()) // connection failedfmt.Println(errors.FormatChain(err)) // initialize service: connection failedfmt.Println(errors.CollectUserTags(err))

With logging and results:

import (
"github.com/pubgo/funk/v2/log""github.com/pubgo/funk/v2/result"
)
log.Error().Err(err).Msg("operation failed") // adds error_chain, error_tags, error_idr:=result.ErrOf(err)
_=r.Message()
_=r.Tags()

Result Types

import"github.com/pubgo/funk/v2/result"// Create a successful resultres:=result.OK(42)
// Create a failed resulterrRes:= result.Fail[int](errors.New("calculation failed"))
// Safely unwrap valuesifvalue, ok:=res.TryUnwrap(); ok {
fmt.Printf("Got value: %d\n", value)
}
// Chain operationsresult:=result.OK(10).
Map(func(xint) int { returnx*2 }).
FlatMap(func(xint) result.Result[int] {
ifx>0 {
returnresult.OK(x+1)
}
return result.Fail[int](errors.New("negative value"))
})

Feature Flags

import"github.com/pubgo/funk/v2/features"// Define a feature flagvardebugMode=features.Bool("debug", false, "Enable debug mode")
// Use the feature flagifdebugMode.Value() {
log.Println("Debug mode enabled")
}

Configuration

import"github.com/pubgo/funk/v2/config"typeConfigstruct {
Serverstruct {
Hoststring`yaml:"host"`Portint`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 fallbackhost:=env.GetOr("SERVER_HOST", "localhost")
// Type-safe environment variable accessport:=env.GetInt("SERVER_PORT", "PORT")
debug:=env.GetBool("DEBUG")

Stack Trace Analysis

import"github.com/pubgo/funk/v2/stack"// Capture current stack traceframes:=stack.Trace()
// Get caller informationcaller:=stack.Caller(0)
fmt.Printf("Called from: %s:%d\n", caller.File, caller.Line)

Modules

  • errors: Enhanced error handling with wrapping, stack traces, tags, and readable error chains
  • 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:

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

License

MIT

About

go common component, include error, log, config, etc...

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages