tool

package module
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: May 20, 2025 License: MIT Imports: 9 Imported by: 3

README

🛠️ Tool Utilities

Go Reference Go Report Card Test Coverage

This library provides a collection of utility functions designed to simplify common tasks and improve code robustness. It includes a main tool package and a safetool sub-package, where functions are designed to return errors instead of panicking.

✨ Features

  • Convenient Utilities: A collection of helper functions for various tasks.
  • Safe Alternatives: The safetool sub-package offers functions that return errors, promoting more resilient error handling.
  • Well-Tested: Includes a comprehensive test suite to ensure reliability.

🚀 Installation

To install the tool package, use go get:

go get -u github.com/iamwavecut/tool

📦 Packages

This repository contains the following main packages:

tool

The main package containing various utility functions. These functions will return zero values or errors instead of panicking on unexpected input or errors.

safetool

The safetool package provides alternative implementations of functions found in the tool package. These "safe" versions are designed to return an error instead of muting errors, allowing for more controlled error handling in your applications.


Common exported functions (with identical interfaces in both packages):
  • In(needle, ...haystack) bool - deprecated in favor of slices.Contains
  • IsZero(comparable) bool - returns true if the value is the zero value for its type
  • NonZero(comparable) comparable - returns the first non-zero value from the input arguments
  • Ptr(any) *any - returns a pointer to the input value
  • RetryFunc(attempts int, sleep time.Duration, f func() error) error - retries a function with exponential backoff
  • Strtr(subject string, oldToNew map[string]string) string - replaces substrings in a string based on a mapping

tool-specific exported functions:
  • Catch(func(error)) - catches panics and calls a function with the error
  • Console(...any) - prints to the console
  • ConvertSlice([]T, Y) []Y - converts a slice of one type to another
  • Err(...any) error - returns an error with the input arguments
  • ExecTemplate(string, []|map) string - executes a template
  • Jsonify(any) safetool.Varchar - returns a Varchar from the input value
  • MultiMute(...any) []any - returns a slice of the input arguments with no latest error
  • Must(error, verbose ?bool) - panics if the error is not nil
  • MustReturn(any, error) any - panics if the error is not nil
  • Objectify(in any, target any) bool - decodes a JSON string into the target object
  • RandInt(min, max int) int - returns a random integer between min and max
  • Recoverer(maxPanics int, f func(), jobID ...string) error - recovers from panics and returns the error
  • Return(any, _ error) any - returns the input value
  • SetLogger(l StdLogger) - sets the logger
  • Try(err error, verbose ?bool) bool - returns true if the error is nil

safetool-specific exported functions:
  • ConvertSlice([]T, Y) ([]Y, error) - converts a slice of one type to another
  • ExecTemplate(string, []|map) (string, error) - executes a template
  • FindRootCaller() string - returns the root caller filepath of the application
  • GetRelativePath(string) (string, error) - returns a relative path from the directory of the root caller to the given filePath
  • Jsonify(any) (safetool.Varchar, error) - returns an encoded JSON string from the input value represented as a Varchar
  • Objectify(in any, target any) error - decodes a JSON string into the target object
  • RandInt(min, max int) (int, error) - returns a random integer between min and max
  • Zero(any) any - returns the zero value for the input type

🤝 Contributing

Contributions are welcome! Please feel free to submit a pull request or open an issue if you have suggestions or find a bug.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📜 License

This project is licensed under the MIT License.

Documentation

Overview

Package tool Useful general purpose tool

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Catch added in v1.0.2

func Catch(fn func(err error))

Catch Recovers from panic and callbacks with error If error is not catchableError, it will panic again May be used as defer, coupled with MustReturn or Must, to override named return values

Usage:

  func example() (val *http.Request, err error) {
	defer tool.Catch(func(caught error) {
		err = caught
 	})

	val = tool.MustReturn(funcThatReturnsValAndErr()) // <- this will be caught if err!=nil
	panic(errors.New("some error")) // <- this will not be caught
	return
}

func Console

func Console(obj ...interface{})

Console Prints %+v of arguments, great to debug stuff

func ConvertSlice added in v1.2.0

func ConvertSlice[T any, Y any](srcSlice []T, destTypedValue Y) []Y

ConvertSlice Return a new slice as `[]dstTypedValue.(type)` cast from the `srcSlice`

func Err added in v1.0.2

func Err(args ...any) error

Err Returns the last argument if it is an error, otherwise nil

func ExecTemplate added in v1.0.8

func ExecTemplate(templateText string, templateVars any) string

func In

func In[T comparable](needle T, haystack ...T) bool

In Checks if element is in a slice Deprecated: Use slices.Contains instead

func IsZero added in v1.3.0

func IsZero[T comparable](v T) bool

IsZero Checks if value is zero

func Jsonify

func Jsonify(s any) safetool.Varchar

Jsonify Returns Varchar implementation of the serialized value, returns empty on error

func MultiMute added in v1.2.0

func MultiMute[T any](a ...T) []T

MultiMute Ignores errors, returns slice of results.

func Must

func Must(err error, verbose ...bool)

Must Tolerates no errors.

func MustReturn added in v1.0.2

func MustReturn[T any](val T, err error) T

MustReturn Tolerates no errors, returns value.

func NonZero added in v1.0.7

func NonZero[T comparable](ts ...T) T

NonZero Returns first non-zero value or zero value if all values are zero

func Objectify

func Objectify[T ~[]byte | ~string](in T, target any) bool

Objectify Unmarshalls value to the target pointer value

func Ptr

func Ptr[T any](n T) *T

Ptr Return a pointer for any passed object

func RandInt

func RandInt[num constraints.Signed](min, max num) num

RandInt Return a random number in specified range.

func Recoverer

func Recoverer[num constraints.Integer](maxPanics num, f func(), jobID ...string) (recovErr error)

Recoverer Recovers job from panic, if maxPanics<0 then infinitely

func RetryFunc

func RetryFunc[num constraints.Signed](attempts num, sleep time.Duration, f func() error) error

RetryFunc Re-runs function if error returned

func Return added in v1.0.2

func Return[T any](val T, _ error) T

Return Ignores errors, returns value.

func SetLogger

func SetLogger(l StdLogger)

SetLogger Sets tool package logger, pass nil to disable logging

func Strtr

func Strtr(subject string, oldToNew map[string]string) string

Strtr Replaces all old string occurrences with new string in subject

func Try

func Try(err error, verbose ...bool) bool

Try Probes the error and returns bool, optionally logs the message.

Types

type LogRus

type LogRus interface {
	StdLogger
	WithError(error) LogRus
	Errorln(...any)
}

type StdLogger

type StdLogger interface {
	Println(...any)
	Panicln(...any)
	Printf(string, ...any)
	Print(...any)
}

type Varchar

type Varchar string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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