goutils

package module
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2025 License: MIT Imports: 14 Imported by: 2

README

Go Function Utilities

There was a time where devs wanted to make things easy (Go), but there are other ways to make things easy.

go get github.com/nitsugaro/[email protected]
Map Tree

Use MapTree to parse an unknown dimentional goutils.DefaultMap{...} without performing a crash for access to a key/sub-key.

Use Cases

  • External Data
  • Unlimited Data to Typed
  • Runtimes like JS
data := goutils.DefaultMap{
		"user": goutils.DefaultMap{
			"name":  "Alice",
			"age":   28,
			"email": "[email protected]",
			"roles": []interface{}{"admin", "editor", "viewer"},
		},
	}

	// Create a TreeMap
	tree := goutils.NewTreeMap(data)

	// --- Basic Get & Value Access ---
	fmt.Println("Name:", tree.Get("user.name").AsStringOr("Unknown"))
	fmt.Println("Age:", tree.Get("user.age").AsIntOr(-1))
	fmt.Println("Email:", tree.Get("user.email").AsStringOr("no email"))

	// --- Check Existence ---
	if tree.IsDefined("user.name") {
		fmt.Println("Name is defined.")
	}
	if !tree.Get("user.password").Exists() {
		fmt.Println("Password not found.")
	}
	if tree.Get("user.undefined").IsEmpty() {
		fmt.Println("Field is nil.")
	}

	// --- Set Value ---
	tree.Set("user.country", "Argentina")
	fmt.Println("Country:", tree.Get("user.country").AsStringOr("No country"))

	// --- Delete Field ---
	tree.Delete("user.email")
	fmt.Println("Email after delete:", tree.Get("user.email").AsStringOr("Deleted"))
Http Client

Use to instance Http Client for requests.

/*
ClientConfig {
	BaseURL         string
	Timeout         time.Duration
	SkipVerifySSL   bool
	TrustedCertPEM  []byte
	ClientCertPEM   []byte mTLS
	ClientKeyPEM    []byte mTLS
	DefaultHeaders  map[string]string
	FollowRedirects bool
}
*/

// Create an HTTP client with custom configuration
client, _ := goutils.NewHttpClient(&goutils.ClientConfig{
	BaseURL:         "https://httpbin.org",
	Timeout:         5 * time.Second,
	FollowRedirects: true,
	DefaultHeaders: map[string]string{
		"my-default-header": "1234",
	},
})

// Add an interceptor (e.g., to inject headers dynamically)
client.AddInterceptor(func(req *http.Request) error {
	req.Header.Add("x-transaction-id", "1234")
	return nil
})

// Make a GET request to /redirect/1
res, _ := client.Request("GET", "/redirect/1", nil, nil)

// Access response data
res.Status         // HTTP status code, e.g., 200
res.Headers        // http.Header (response headers)
res.Body           // []byte (raw body)
res.Duration       // Request duration (time.Duration)
res.Raw            // *http.Response (raw response)

// Print response body as string
fmt.Println(string(res.Body)) // (HTML or JSON, depending on the endpoint)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func All

func All[T any](slice []T, pass func(T, int) bool) bool

func Compact

func Compact[T comparable](slice []T) []T

Removes falsy elements

func DelFirst

func DelFirst[T any](s *[]T) (T, bool)

Remove first element of slice

func DelLast

func DelLast[T any](s *[]T) (T, bool)

Remove last element of slice

func Filter

func Filter[T any](slice []T, keep func(T, int) bool) []T

func Find

func Find[T any](slice []T, pass func(T, int) bool) T

func FindIndex

func FindIndex[T any](slice []T, pass func(T) bool) int

func ForEach

func ForEach[T any](slice []T, fn func(item T, index int))

func ForEachAsync

func ForEachAsync[T any](collection []T, fn func(item T, index int))

All functions are called async

func Map

func Map[T any, K any](slice []T, transform func(T, int) K) []K

func MapAsync

func MapAsync[T any, K any](collection []T, fn func(item T, index int) K) []K

All functions are called async with waits for all to finish

func Reverse

func Reverse[T any](slice []T) []T

func Some

func Some[T any](slice []T, pass func(T, int) bool) bool

Types

type ClientConfig

type ClientConfig struct {
	Timeout         time.Duration
	SkipVerifySSL   bool
	TrustedCertPEM  []byte
	ClientCertPEM   []byte
	ClientKeyPEM    []byte
	DefaultHeaders  map[string]string
	FollowRedirects bool
}

type DefaultMap

type DefaultMap = map[string]any

type HttpClient

type HttpClient struct {
	// contains filtered or unexported fields
}

func NewHttpClient

func NewHttpClient(cfg *ClientConfig) (*HttpClient, error)

func (*HttpClient) AddInterceptor

func (hc *HttpClient) AddInterceptor(i Interceptor)

func (*HttpClient) Request

func (hc *HttpClient) Request(method, uri string, headers map[string]string, body []byte) (*Response, error)

func (*HttpClient) RequestWithContext added in v1.5.0

func (hc *HttpClient) RequestWithContext(ctx context.Context, method, uri string, headers map[string]string, body []byte) (*Response, error)

func (*HttpClient) SetBaseUrl added in v1.0.1

func (hc *HttpClient) SetBaseUrl(baseUrl string)

type Interceptor

type Interceptor func(req *http.Request) error

type Response

type Response struct {
	RequestUri string
	Status     int
	Headers    http.Header
	Body       []byte
	Raw        *http.Response
	Duration   time.Duration
}

type SafeTreeMap added in v1.5.0

type SafeTreeMap struct {
	// contains filtered or unexported fields
}

func (*SafeTreeMap) AsAny added in v1.5.0

func (s *SafeTreeMap) AsAny() (any, error)

func (*SafeTreeMap) AsAnyOr added in v1.5.0

func (s *SafeTreeMap) AsAnyOr(def any) any

func (*SafeTreeMap) AsAnySlice added in v1.5.0

func (s *SafeTreeMap) AsAnySlice() []any

func (*SafeTreeMap) AsBool added in v1.5.0

func (s *SafeTreeMap) AsBool() (bool, error)

func (*SafeTreeMap) AsBoolOr added in v1.5.0

func (s *SafeTreeMap) AsBoolOr(def bool) bool

func (*SafeTreeMap) AsBoolSlice added in v1.5.0

func (s *SafeTreeMap) AsBoolSlice() []bool

func (*SafeTreeMap) AsFloat added in v1.5.0

func (s *SafeTreeMap) AsFloat() (float64, error)

func (*SafeTreeMap) AsFloatOr added in v1.5.0

func (s *SafeTreeMap) AsFloatOr(def float64) float64

func (*SafeTreeMap) AsInt added in v1.5.0

func (s *SafeTreeMap) AsInt() (int64, error)

func (*SafeTreeMap) AsIntOr added in v1.5.0

func (s *SafeTreeMap) AsIntOr(def int64) int64

func (*SafeTreeMap) AsIntSlice added in v1.5.0

func (s *SafeTreeMap) AsIntSlice() []int64

func (*SafeTreeMap) AsMap added in v1.5.0

func (s *SafeTreeMap) AsMap() (DefaultMap, error)

func (*SafeTreeMap) AsSlice added in v1.5.0

func (s *SafeTreeMap) AsSlice() ([]TreeMapImpl, error)

func (*SafeTreeMap) AsSliceOf added in v1.5.0

func (s *SafeTreeMap) AsSliceOf(target []any) error

------------------- Struct / Slice Conversions -------------------

func (*SafeTreeMap) AsStrSlice added in v1.5.0

func (s *SafeTreeMap) AsStrSlice() []string

------------------- Slice Helpers -------------------

func (*SafeTreeMap) AsString added in v1.5.0

func (s *SafeTreeMap) AsString() (string, error)

------------------- Value Conversions -------------------

func (*SafeTreeMap) AsStringOr added in v1.5.0

func (s *SafeTreeMap) AsStringOr(def string) string

------------------- Default Fallbacks -------------------

func (*SafeTreeMap) AsStruct added in v1.5.0

func (s *SafeTreeMap) AsStruct(target any) error

func (*SafeTreeMap) Clone added in v1.5.0

func (s *SafeTreeMap) Clone() TreeMapImpl

func (*SafeTreeMap) Delete added in v1.5.0

func (s *SafeTreeMap) Delete(path string) TreeMapImpl

func (*SafeTreeMap) Exists added in v1.5.2

func (s *SafeTreeMap) Exists() bool

func (*SafeTreeMap) Get added in v1.5.0

func (s *SafeTreeMap) Get(path string) TreeMapImpl

------------------- Core -------------------

func (*SafeTreeMap) IsDefined added in v1.5.1

func (s *SafeTreeMap) IsDefined(path string) bool

func (*SafeTreeMap) IsEmpty added in v1.5.2

func (s *SafeTreeMap) IsEmpty() bool

func (*SafeTreeMap) Or added in v1.5.1

func (s *SafeTreeMap) Or(path string) TreeMapImpl

func (*SafeTreeMap) Set added in v1.5.0

func (s *SafeTreeMap) Set(path string, value any) TreeMapImpl

func (*SafeTreeMap) ToJsonString added in v1.5.0

func (s *SafeTreeMap) ToJsonString(pretty bool) string

func (*SafeTreeMap) TryDelete added in v1.5.0

func (s *SafeTreeMap) TryDelete(path string) TreeMapImpl

type TreeMap

type TreeMap struct {
	// contains filtered or unexported fields
}

func (*TreeMap) AsAny added in v1.4.0

func (d *TreeMap) AsAny() (any, error)

func (*TreeMap) AsAnyOr added in v1.4.0

func (d *TreeMap) AsAnyOr(def any) any

func (*TreeMap) AsAnySlice added in v1.5.0

func (d *TreeMap) AsAnySlice() []any

func (*TreeMap) AsBool

func (d *TreeMap) AsBool() (bool, error)

func (*TreeMap) AsBoolOr added in v1.3.0

func (d *TreeMap) AsBoolOr(def bool) bool

func (*TreeMap) AsBoolSlice added in v1.5.0

func (d *TreeMap) AsBoolSlice() []bool

func (*TreeMap) AsFloat

func (d *TreeMap) AsFloat() (float64, error)

func (*TreeMap) AsFloatOr added in v1.3.0

func (d *TreeMap) AsFloatOr(def float64) float64

func (*TreeMap) AsInt

func (d *TreeMap) AsInt() (int64, error)

func (*TreeMap) AsIntOr added in v1.3.0

func (d *TreeMap) AsIntOr(def int64) int64

func (*TreeMap) AsIntSlice added in v1.5.0

func (d *TreeMap) AsIntSlice() []int64

func (*TreeMap) AsMap

func (d *TreeMap) AsMap() (DefaultMap, error)

func (*TreeMap) AsSlice

func (d *TreeMap) AsSlice() ([]TreeMapImpl, error)

func (*TreeMap) AsSliceOf

func (d *TreeMap) AsSliceOf(target []any) error

------------------- Struct / Slice Conversions -------------------

func (*TreeMap) AsStrSlice added in v1.5.0

func (d *TreeMap) AsStrSlice() []string

------------------- AsStrSlice / AsIntSlice / etc -------------------

func (*TreeMap) AsString

func (d *TreeMap) AsString() (string, error)

------------------- Value Conversions -------------------

func (*TreeMap) AsStringOr added in v1.3.0

func (d *TreeMap) AsStringOr(def string) string

------------------- Default Fallbacks -------------------

func (*TreeMap) AsStruct

func (d *TreeMap) AsStruct(target any) error

func (*TreeMap) Clone added in v1.5.0

func (d *TreeMap) Clone() TreeMapImpl

func (*TreeMap) Delete

func (d *TreeMap) Delete(path string) TreeMapImpl

delete path key and returns a new treemap with from path value

func (*TreeMap) Exists added in v1.3.0

func (d *TreeMap) Exists() bool

func (*TreeMap) Get

func (d *TreeMap) Get(path string) TreeMapImpl

------------------- Get -------------------

func (*TreeMap) IsDefined

func (d *TreeMap) IsDefined(path string) bool

------------------- Status -------------------

func (*TreeMap) IsEmpty added in v1.3.0

func (d *TreeMap) IsEmpty() bool

func (*TreeMap) Or added in v1.3.0

func (d *TreeMap) Or(path string) TreeMapImpl

func (*TreeMap) Set

func (d *TreeMap) Set(path string, value any) TreeMapImpl

------------------- Set -------------------

func (*TreeMap) ToJsonString

func (d *TreeMap) ToJsonString(pretty bool) string

func (*TreeMap) TryDelete added in v1.4.0

func (d *TreeMap) TryDelete(path string) TreeMapImpl

delete path key and returns the root treemap

type TreeMapImpl added in v1.5.1

type TreeMapImpl interface {
	Get(path string) TreeMapImpl
	IsDefined(path string) bool
	Exists() bool
	IsEmpty() bool
	Or(path string) TreeMapImpl
	Set(path string, value any) TreeMapImpl
	Delete(path string) TreeMapImpl
	TryDelete(path string) TreeMapImpl
	Clone() TreeMapImpl
	ToJsonString(pretty bool) string
	AsMap() (DefaultMap, error)
	AsSlice() ([]TreeMapImpl, error)
	AsString() (string, error)
	AsInt() (int64, error)
	AsFloat() (float64, error)
	AsBool() (bool, error)
	AsAny() (any, error)
	AsSliceOf(target []any) error
	AsStruct(target any) error
	AsStringOr(def string) string
	AsIntOr(def int64) int64
	AsFloatOr(def float64) float64
	AsBoolOr(def bool) bool
	AsAnyOr(def any) any
	AsStrSlice() []string
	AsIntSlice() []int64
	AsBoolSlice() []bool
	AsAnySlice() []any
	// contains filtered or unexported methods
}

func NewSyncTreeMap added in v1.5.0

func NewSyncTreeMap(data ...any) TreeMapImpl

func NewTreeMap

func NewTreeMap(data ...any) TreeMapImpl

------------------- Constructors -------------------

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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