gosl

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2023 License: Apache-2.0 Imports: 22 Imported by: 3

README

gosl – The Go Snippet Library

Go version Go report Code coverage License

The Go Snippet Library (or gosl for a short) provides a snippet collection for working with routine operations in your Go programs with a super user-friendly API and the most efficient performance (see the benchmarks section).

⚡️ Quick start

Simply add gosl to your project:

go get github.com/koddr/gosl

Add the needed snippet to your Go program, like this:

import "github.com/koddr/gosl"

type user struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

func main() {
    b := []byte("Hello, World!")
    
    s, err := gosl.ToString(b) // convert byte slice to string
    
    // ...
    
    json := []byte(`{"id":1,"name":"Viktor"}`)
    model := &user{}

    u, err := gosl.Unmarshal(json, model) // unmarshal JSON data to struct

    // ...
}

...or like this to have access to snippets as embedded struct:

import "github.com/koddr/gosl"

type App struct {
    // ...
    
    utils    *gosl.Utility                         // add regular snippets
    genUtils *gosl.GenericUtility[any, comparable] // add generic snippets
}

func (a *App) handleSomething() error {
    // ...
    
    s, err := a.utils.ToString(b) // convert byte slice to string
    
    // ...
    
    u, err := a.genUtils.Unmarshal(json, model) // unmarshal JSON data to struct
    
    // ...
}

✨ Usage

Basic usage and full code examples of all functions of the gosl package, you can find on the pkg.go.dev page.

The package provides two categories of functions: regular and universal using generics (Go 1.18+). Also, note that some features will only work correctly on Go 1.20 and above.

🔨 Regular functions

The regular functions of the gosl package are aimed at solving one single task with the smallest possible allocation of your machine's resources.

Concat

Concatenates strings s to the one string:

s1 := "this "
s2 := "is "
s3 := "my string"

s := gosl.Concat(s1, s2, s3) // "this is my string"
ContainsCaseInsensitive

Reports if string substr is within string s (case-insensitive by default):

s := "Hello, WORLD!"
substr := "r"

b := gosl.ContainsCaseInsensitive(s, substr) // true
IsFileExist

Reports whether a file exists on the specified path:

p := filepath.Clean("~/Downloads/file.csv")

b := gosl.IsFileExist(p) // true|false
IsDirExist

Reports whether a dir exists on the specified path:

p := filepath.Clean("~/Downloads/my-folder")

b := gosl.IsDirExist(p) // true|false
RandomString

Generates a (really) random string with a given size:

size := 8

s, err := gosl.RandomString(size) // string, like "34f4ey7e"
if err != nil {
    log.Fatal(err)
}
RenderStyled

Renders a styled string with a given lipgloss.Style template:

tmpl := lipgloss.NewStyle().Foreground(lipgloss.Color("42")).Margin(1)

s := gosl.RenderStyled("This is a styled text", tmpl) // styled string

This function is a more comfortable wrapper for the charmbracelet/lipgloss library.

ToString

Converts byte slice b to string or error:

b := []byte("Hello, World!")

s, err := gosl.ToString(b) // "Hello, World!"
if err != nil {
    log.Fatal(err)
}
ToBytes

Converts string s to byte slice or error:

s := "Hello, World!"

b, err := gosl.ToBytes(s) // [48 65 6c ...]
if err != nil {
    log.Fatal(err)
}
ModifyByValue

Modify an unknown key in the given map[string]any by it value:

m := map[string]any{"order": map[string]any{"total_cost": 100}}
foundValue := 100
newValue := 250

isFound, result := gosl.ModifyByValue(m, foundValue, newValue)

Supports nested maps, but only if their type is map[string]any.

🛠️ Universal functions

The universal (or generic) functions of the gosl package are aimed at solving one particular task with the smallest possible allocation of your machine's resources, but can be applied to a huge number of user types.

💡 Hint: enjoy the benefits of using Go 1.18+ generics today! Instead of writing a regular function for each of your types, just use one generic function from the list below.

Equals

Compares two values of type T, return true if they are equal:

s1 := "hello"
s2 := "hello"

b := gosl.Equals(s1, s2) // true
NotEquals

Compares two values of type T, return true if they are not equal:

s1 := 42
s2 := 64

b := gosl.NotEquals(s1, s2) // true
ContainsInSlice

Reports if value v is within slice s:

s := []string{"one", "two", "three"}
v := "two"

b := gosl.ContainsInSlice(s, v) // true
ContainsInMap

Reports if key k is within map m:

m := map[string]int{"one": 1, "two": 2, "three": 3}
k := "two"

b := gosl.ContainsInMap(m, k) // true
ParseFileToStruct

Parses the given file from path to struct *T.

Create structured file in any of the supported file formats (JSON, YAML, TOML, or HCL) with the main data to parse (for example, ./config.yml):

host: https://my-server.com/api/v1
port: '3000'

Create a new struct for a parsing data (for example, server):

type server struct {
    Host string `koanf:"host"`
    Port string `koanf:"port"`
}

Add to your Go program:

pathToFile := "./file.yml" // or any URL to file in the supported format
structToParse := &server{}

srv, err := gosl.ParseFileToStruct(pathToFile, structToParse)
if err != nil {
    log.Fatal(err)
}

// Results:
//  srv.Host = "https://my-server.com/api/v1"
//  srv.Port = "3000"

💡 Note: The structured file can be placed both locally (by system path) and accessible via HTTP (by URL).

This generic function is based on the knadh/koanf library.

ParseFileWithEnvToStruct

Parses the given file from path to struct *T with an (optional) environment variables for a secret data.

Set your secret data to environment variables with a personal prefix (for example, MY_CONFIG):

export MY_CONFIG_TOKEN=my-secret-1234567

Create structured file in any of the supported file formats (JSON, YAML, TOML, or HCL) with the main data to parse (for example, ./config.yml):

url: https://my-server.com/api/v1
auth_type: Bearer
token: '{{ MY_CONFIG_TOKEN }}'

Create a new struct for a parsing data (for example, config):

type config struct {
    URL      string `koanf:"url"`
    AuthType string `koanf:"auth_type"`
    Token    string `koanf:"token"`
}

Add to your Go program:

pathToFile := "./file.yml" // or any URL to file in the supported format
envPrefix := "MY_CONFIG"   // or "", if you don't want to use env
structToParse := &config{}

cfg, err := gosl.ParseFileWithEnvToStruct(pathToFile, envPrefix, structToParse)
if err != nil {
    log.Fatal(err)
}

// Results:
//  cfg.URL = "https://my-server.com/api/v1"
//  cfg.AuthType = "Bearer"
//  cfg.Token = "my-secret-1234567"

💡 Note: The structured file can be placed both locally (by system path) and accessible via HTTP (by URL).

This generic function is based on the knadh/koanf library.

Marshal

Marshal struct user to JSON data j (byte slice) or error:

type user struct {
ID   int    `json:"id"`
    Name string `json:"name"`
}

u := &user{}

j, err := gosl.Marshal(u) // {"id": 0, "name": ""}
if err != nil {
    log.Fatal(err)
}

This generic function is a 100% compatible drop-in replacement for the standard encoding/json library.

Unmarshal

Unmarshal JSON data j (byte slice) to struct user or error:

type user struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

j := []byte(`{"id":1,"name":"Viktor"}`)
m := &user{}

u, err := gosl.Unmarshal(j, m) // [id:1 name:Viktor]
if err != nil {
    log.Fatal(err)
}

This generic function is a 100% compatible drop-in replacement for the standard encoding/json library.

⏱️ Benchmarks

Run benchmarks on your machine by following command:

go test -v ./... -bench . -run ^$ -benchmem

And this is my results for all functions on test stand (Apple Macbook Air M1, 16 Gb RAM, macOS 13.3.1):

BenchmarkEquals-8                               	319768486	         3.591 ns/op	       0 B/op	       0 allocs/op

BenchmarkNotEquals-8                            	1000000000	         0.5136 ns/op	       0 B/op	       0 allocs/op

BenchmarkConcat_String2-8                       	59083364	        19.91 ns/op	      32 B/op	       1 allocs/op
BenchmarkConcat_String8-8                       	27004447	        44.21 ns/op	     128 B/op	       1 allocs/op
BenchmarkConcat_String32-8                      	 9373778	       127.4 ns/op	     448 B/op	       1 allocs/op

BenchmarkToString_HelloWorld-8                  	100000000	        10.56 ns/op	      16 B/op	       1 allocs/op

BenchmarkToBytes_HelloWorld-8                   	1000000000	         0.6288 ns/op	   0 B/op	       0 allocs/op

BenchmarkRandomString_Size1-8                   	 3649489	       328.4 ns/op	       6 B/op	       3 allocs/op
BenchmarkRandomString_Size8-8                   	 3397297	       351.8 ns/op	      24 B/op	       3 allocs/op
BenchmarkRandomString_Size64-8                  	 2313856	       517.9 ns/op	     160 B/op	       3 allocs/op
BenchmarkRandomString_Size512-8                 	 1425562	       837.8 ns/op	    1280 B/op	       3 allocs/op
BenchmarkRandomString_Size4096-8                	  186254	      6331 ns/op	   10240 B/op	       3 allocs/op

BenchmarkMarshal_StructField_4-8                	 8584442	       139.9 ns/op	      48 B/op	       3 allocs/op
BenchmarkMarshal_StructField_16-8               	 2879486	       416.6 ns/op	     192 B/op	       3 allocs/op

BenchmarkUnmarshal_StructField_4-8              	 6960462	       169.3 ns/op	      32 B/op	       3 allocs/op
BenchmarkUnmarshal_StructField_16-8             	  774032	      1534 ns/op	     864 B/op	      45 allocs/op

BenchmarkModifyByValue-8                        	 2824796	       423.2 ns/op	     704 B/op	       6 allocs/op

BenchmarkParseFileToStruct-8                    	   39021	     30177 ns/op	    6184 B/op	     109 allocs/op

BenchmarkParseFileWithEnvToStruct-8             	   28864	     41873 ns/op	   12232 B/op	     219 allocs/op

BenchmarkRenderStyled-8                         	 1459971	       821.5 ns/op	     440 B/op	      12 allocs/op

BenchmarkContainsCaseInsensitive_HelloWorld-8   	24856041	        48.46 ns/op	      16 B/op	       1 allocs/op
BenchmarkContainsCaseInsensitive_LoremIpsum-8   	 1827114	       656.4 ns/op	     448 B/op	       1 allocs/op

BenchmarkContainsInSlice-8                      	122999034	         9.758 ns/op	   0 B/op	       0 allocs/op

BenchmarkContainsInMap-8                        	19123504	        62.61 ns/op	       0 B/op	       0 allocs/op

BenchmarkIsFileExist-8                          	  395916	      2941 ns/op	     240 B/op	       2 allocs/op

BenchmarkIsDirExist-8                           	  437505	      2696 ns/op	     224 B/op	       2 allocs/op

💡 Motivation

As you already know from my previous projects, I take an approach to software development that makes the developer's life totally easy.

Why repeat the same snippet, for example, to translate a byte slice to a string if you can add the most efficient solution to the library once and import it where you need it? Exactly right! It's an unnecessary cognitive load for those who will read your code in the future (and for you as well).

It is for these reasons that The Go Snippet Library (or gosl for a short) provides a snippet collection for working with routine operations in your Go programs with a super user-friendly API and the most efficient performance.

🏆 A win-win cooperation

And now, I invite you to participate in this project! Let's work together to create the largest and most useful library of snippets for Go programs on the web today.

  • Issues: ask questions and submit your features.
  • Pull requests: send your snippets or improvements to the current.

Your PRs & issues are welcome! Thank you 😘

⚠️ License

gosl is free and open-source software licensed under the Apache 2.0 License, created and supported with 🩵 for people and robots by Vic Shóstak.

Documentation

Overview

Package gosl provides a snippet collection for working with routine operations in your Go programs with a super user-friendly API and the most efficient performance.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Concat

func Concat(s ...string) string

Concat concatenate strings using the built-in copy and "unsafe" package with unsafe.String function.

If s has no elements returns zero-value for a string.

Example:

package main

import (
	"fmt"

	"github.com/koddr/gosl"
)

func main() {
	s1 := "this "
	s2 := "is "
	s3 := "my string"

	s := gosl.Concat(s1, s2, s3)

	fmt.Println(s)
}

func ContainsCaseInsensitive

func ContainsCaseInsensitive(s, substr string) bool

ContainsCaseInsensitive reports if substr is within s string using built-in "strings" package with strings.Contains. Case-insensitive for input values by default.

If s and/or substr have a zero-value, returns false for bool.

Example:

package main

import (
	"fmt"

	"github.com/koddr/gosl"
)

func main() {
	s := "this is my string"
	substr := "my"

	b := gosl.ContainsCaseInsensitive(s, substr)

	fmt.Println(b)
}

func ContainsInMap

func ContainsInMap[T any, K comparable](m map[K]T, key K) bool

ContainsInMap reports if key T is within map[T]K.

If m has a zero-value, returns false for bool.

Example:

package main

import (
	"fmt"

	"github.com/koddr/gosl"
)

func main() {
	m := map[string]int{"one": 1, "two": 2, "three": 3}
	key := "two"

	b := gosl.ContainsInMap(m, key)

	fmt.Println(b)
}

func ContainsInSlice

func ContainsInSlice[T comparable](s []T, value T) bool

ContainsInSlice reports if value T is within slice []T.

If s has a zero-value, returns false for bool.

Example:

package main

import (
	"fmt"

	"github.com/koddr/gosl"
)

func main() {
	s := []string{"one", "two", "three"}
	value := "two"

	b := gosl.ContainsInSlice(s, value)

	fmt.Println(b)
}

func Equals added in v1.2.0

func Equals[T comparable](value1, value2 T) bool

Equals compares two values of type T, returns true if they are equal.

Example:

package main

import (
	"fmt"

	"github.com/koddr/gosl"
)

func main() {
	s1 := "hello"
	s2 := "hello"

	b := gosl.Equals(s1, s2)

	fmt.Println(b)
}

func IsDirExist added in v1.3.0

func IsDirExist(path string) bool

IsDirExist reports whether a dir exists on the specified path.

If path has a zero-value or is file, returns false for bool.

Example:

package main

import (
	"fmt"

	"github.com/koddr/gosl"
)

func main() {
	p := filepath.Clean("~/Downloads/my-folder")

	b := gosl.IsDirExist(p)

	fmt.Println(b)
}

func IsFileExist added in v1.3.0

func IsFileExist(path string) bool

IsFileExist reports whether a file exists on the specified path.

If path has a zero-value or is dir, returns false for bool.

Example:

package main

import (
	"fmt"

	"github.com/koddr/gosl"
)

func main() {
	p := filepath.Clean("~/Downloads/file.csv")

	b := gosl.IsFileExist(p)

	fmt.Println(b)
}

func Marshal

func Marshal[T any](model *T) ([]byte, error)

Marshal converts struct *T to JSON data (byte slice) using jsoniter.Marshal with a default configuration. A 100% compatible drop-in replacement of "encoding/json" standard lib.

If err != nil returns zero-value for a byte slice and error.

Example:

package main

import (
	"fmt"
	"log"

	"github.com/koddr/gosl"
)

type user struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

func main() {
	u := &user{ID: 1, Name: "Viktor"}

	json, err := gosl.Marshal(u)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(json))
}

func ModifyByValue added in v1.5.0

func ModifyByValue(m map[string]any, foundValue, newValue any) (foundKey bool, results map[string]any)

ModifyByValue modify an unknown key in the given map[string]any by it value. Supports nested maps, but only if their type is map[string]any.

Example:

package main

import (
	"fmt"

	"github.com/koddr/gosl"
)

func main() {
	m := map[string]any{"order": map[string]any{"total_cost": 100}}
	foundValue := 100
	newValue := 250

	isFound, result := gosl.ModifyByValue(m, foundValue, newValue)

	fmt.Println(isFound, result)
}

func NotEquals added in v1.2.0

func NotEquals[T comparable](value1, value2 T) bool

NotEquals compares two values of type T, returns true if they are not equal.

Example:

package main

import (
	"fmt"

	"github.com/koddr/gosl"
)

func main() {
	s1 := "hello"
	s2 := "world"

	b := gosl.NotEquals(s1, s2)

	fmt.Println(b)
}

func ParseFileToStruct added in v1.6.0

func ParseFileToStruct[T any](path string, model *T) (*T, error)

ParseFileToStruct parses the given file from path to struct *T using "knadh/koanf" package.

You can use any of the supported file formats (JSON, YAML, TOML, or HCL). The structured file can be placed both locally (by system path) and accessible via HTTP (by URL).

If err != nil, returns zero-value for a struct and error.

Example:

package main

import (
	"fmt"
	"log"

	"github.com/koddr/gosl"
)

type server struct {
	Host string `koanf:"host"`
	Port string `koanf:"port"`
}

func main() {
	pathToFile := "path/to/server.json"
	structToParse := &server{}

	srv, err := gosl.ParseFileToStruct(pathToFile, structToParse)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(srv)
}

func ParseFileWithEnvToStruct added in v1.4.0

func ParseFileWithEnvToStruct[T any](path, envPrefix string, model *T) (*T, error)

ParseFileWithEnvToStruct parses the given file from path to struct *T using "knadh/koanf" package with an (optional) environment variables for a secret data.

You can use any of the supported file formats (JSON, YAML, TOML, or HCL). The structured file can be placed both locally (by system path) and accessible via HTTP (by URL).

If err != nil, returns zero-value for a struct and error.

Example:

package main

import (
	"fmt"
	"log"

	"github.com/koddr/gosl"
)

type config struct {
	ServerURL string `koanf:"server_url"`
	AuthType  string `koanf:"auth_type"`
	Token     string `koanf:"token"`
}

func main() {
	pathToFile := "https://github.com/user/repo/config.yaml"
	envPrefix := "MY_CONFIG" // for ex., MY_CONFIG_TOKEN=my-secret-1234567
	structToParse := &config{}

	cfg, err := gosl.ParseFileWithEnvToStruct(pathToFile, envPrefix, structToParse)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(cfg)
}

func RandomString

func RandomString(size int) (string, error)

RandomString generates a random string with a given size using built-in "crypto/rand" and "encoding/hex" packages.

If err != nil returns zero-value for a string and error.

Example:

package main

import (
	"fmt"
	"log"

	"github.com/koddr/gosl"
)

func main() {
	s, err := gosl.RandomString(8)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s)
}

func RenderStyled added in v1.1.0

func RenderStyled(str string, template lipgloss.Style) string

RenderStyled render a styled string with a given lipgloss.Style template using "charmbracelet/lipgloss" package.

If s have an "" (empty) value returns zero-value for a string.

Example:

package main

import (
	"fmt"
	"log"

	"github.com/charmbracelet/lipgloss"
	"github.com/koddr/gosl"
)

func main() {
	tmpl := lipgloss.NewStyle().Foreground(lipgloss.Color("42")).Margin(1)

	s := gosl.RenderStyled("This is a styled text", tmpl)

	fmt.Println(s)
}

func ToBytes

func ToBytes(s string) ([]byte, error)

ToBytes converts string to byte slice using the built-in "unsafe" package with unsafe.Slice function.

If err != nil returns zero-value for a byte slice and error.

Example:

package main

import (
	"fmt"
	"log"

	"github.com/koddr/gosl"
)

func main() {
	s := "this is my string"

	b, err := gosl.ToBytes(s)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(b))
}

func ToString

func ToString(b []byte) (string, error)

ToString converts byte slice to string using the built-in "unsafe" package with unsafe.String function.

If err != nil returns zero-value for a string and error.

Example:

package main

import (
	"fmt"
	"log"

	"github.com/koddr/gosl"
)

func main() {
	b := []byte("this is my string")

	s, err := gosl.ToString(b)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s)
}

func Unmarshal

func Unmarshal[T any](data []byte, model *T) (*T, error)

Unmarshal converts JSON data (byte slice) to struct *T using jsoniter.Unmarshal with a default configuration. A 100% compatible drop-in replacement of "encoding/json" standard lib.

If err != nil returns zero-value for a struct and error.

Example:

package main

import (
	"fmt"
	"log"

	"github.com/koddr/gosl"
)

type user struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

func main() {
	json := []byte(`{"id":1,"name":"Viktor"}`)
	model := &user{}

	u, err := gosl.Unmarshal(json, model)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(u)
}

Types

type GenericUtility

type GenericUtility[T any, K comparable] struct{}

GenericUtility represents struct with T any and K comparable types for a generic function.

func (*GenericUtility[T, K]) ContainsInMap

func (g *GenericUtility[T, K]) ContainsInMap(m map[K]T, key K) bool

ContainsInMap reports if key T is within map[T]K.

If m have a zero-value returns false for a bool.

func (*GenericUtility[T, K]) ContainsInSlice

func (g *GenericUtility[T, K]) ContainsInSlice(s []K, value K) bool

ContainsInSlice reports if value T is within slice []T.

If s have a zero-value returns false for a bool.

func (*GenericUtility[T, K]) Equals added in v1.2.0

func (g *GenericUtility[T, K]) Equals(value1, value2 K) bool

Equals compares two values of type K, returns true if they are equal.

func (*GenericUtility[T, K]) Marshal

func (g *GenericUtility[T, K]) Marshal(model *T) ([]byte, error)

Marshal converts struct *T to JSON data (byte slice) using jsoniter.Marshal with a default configuration. A 100% compatible drop-in replacement of "encoding/json" standard lib.

If err != nil returns zero-value for a byte slice and error.

func (*GenericUtility[T, K]) NotEquals added in v1.2.0

func (g *GenericUtility[T, K]) NotEquals(value1, value2 K) bool

NotEquals compares two values of type K, returns true if they are not equal.

func (*GenericUtility[T, K]) ParseFileToStruct added in v1.6.0

func (g *GenericUtility[T, K]) ParseFileToStruct(path string, model *T) (*T, error)

ParseFileToStruct parses the given file from path to struct *T using "knadh/koanf" package.

You can use any of the supported file formats (JSON, YAML, TOML, or HCL). The structured file can be placed both locally (by system path) and accessible via HTTP (by URL).

If err != nil, returns zero-value for a struct and error.

func (*GenericUtility[T, K]) ParseFileWithEnvToStruct added in v1.4.0

func (g *GenericUtility[T, K]) ParseFileWithEnvToStruct(path, envPrefix string, model *T) (*T, error)

ParseFileWithEnvToStruct parses the given file from path to struct *T using "knadh/koanf" package with an (optional) environment variables for a secret data.

You can use any of the supported file formats (JSON, YAML, TOML, or HCL). The structured file can be placed both locally (by system path) and accessible via HTTP (by URL).

If err != nil, returns zero-value for a struct and error.

func (*GenericUtility[T, K]) Unmarshal

func (g *GenericUtility[T, K]) Unmarshal(data []byte, model *T) (*T, error)

Unmarshal converts JSON data (byte slice) to struct *T using jsoniter.Unmarshal with a default configuration. A 100% compatible drop-in replacement of "encoding/json" standard lib.

If err != nil returns zero-value for a struct and error.

type Utility

type Utility struct{}

Utility represents struct for a regular function.

func (*Utility) Concat

func (u *Utility) Concat(s ...string) string

Concat concatenate strings using the built-in copy and "unsafe" package with unsafe.String function.

If s has no elements returns zero-value for a string.

func (*Utility) ContainsCaseInsensitive

func (u *Utility) ContainsCaseInsensitive(s, substr string) bool

ContainsCaseInsensitive reports if substr is within s string using built-in "strings" package with strings.Contains. Case-insensitive for input values by default.

If s and/or substr have an "" (empty) value returns false for a bool.

func (*Utility) IsDirExist added in v1.3.0

func (u *Utility) IsDirExist(path string) bool

IsDirExist reports whether a dir exists on the specified path.

func (*Utility) IsFileExist added in v1.3.0

func (u *Utility) IsFileExist(path string) bool

IsFileExist reports whether a file exists on the specified path.

func (*Utility) ModifyByValue added in v1.5.0

func (u *Utility) ModifyByValue(m map[string]any, foundValue, newValue any) (foundKey bool, results map[string]any)

ModifyByValue modify an unknown key in the given map[string]any by it value. Supports nested maps, but only if their type is map[string]any.

func (*Utility) RandomString

func (u *Utility) RandomString(size int) (string, error)

RandomString generates a random string with a given size using built-in "crypto/rand" and "encoding/hex" packages.

If err != nil returns zero-value for a string and error.

func (*Utility) RenderStyled added in v1.1.0

func (u *Utility) RenderStyled(s string, template lipgloss.Style) string

RenderStyled render a styled string with a given lipgloss.Style template using "charmbracelet/lipgloss" package.

If s have an "" (empty) value returns zero-value for a string.

func (*Utility) ToBytes

func (u *Utility) ToBytes(s string) ([]byte, error)

ToBytes converts string to byte slice using the built-in "unsafe" package with unsafe.Slice function.

If err != nil returns zero-value for a byte slice and error.

func (*Utility) ToString

func (u *Utility) ToString(b []byte) (string, error)

ToString converts byte slice to string using the built-in "unsafe" package with unsafe.String function.

If err != nil returns zero-value for a string and error.

Jump to

Keyboard shortcuts

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