A collection of Go utilities for various tasks.
To install the package, run the following command:
go get github.com/jkaninda/go-utilsimport "github.com/jkaninda/go-utils"- Purpose: Performs a deep copy of the
fromValuestruct (or any value) into thetoValuestruct by marshalling thefromValueto JSON and unmarshalling it into thetoValue. This ensures that nested structs, slices, and maps are also copied deeply. - Parameters:
toValue: The destination struct (must be a pointer to a struct) to copy into.fromValue: The source struct (or any value) to copy from.
- Returns: An error if:
- The
toValueis not a pointer to a struct. - JSON marshalling or unmarshalling fails.
- The
- Example:
type Source struct { Name string Age int Email string } type Destination struct { Name string Age int Email string } src := Source{Name: "John", Age: 30, Email: "[email protected]"} dest := Destination{} err := DeepCopy(&dest, src) if err != nil { fmt.Println("Error:", err) } else { fmt.Printf("Destination: %+v\n", dest) } // Output: Destination: {Name:John Age:30 Email:[email protected]}
type Source struct {
Name string
Age int
Email string
}
type Destination struct {
Name string
Age int
Email string
}
src := Source{Name: "Alice", Age: 25, Email: "[email protected]"}
dest := Destination{}
err := DeepCopy(&dest, src)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Destination: %+v\n", dest)
}
// Output: Destination: {Name:Alice Age:25 Email:[email protected]}type Source struct {
Name string
Age int
}
type Destination struct {
Name string
Email string
}
src := Source{Name: "Bob", Age: 30}
dest := Destination{Email: "[email protected]"}
err := DeepCopy(&dest, src)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Destination: %+v\n", dest)
}
// Output: Destination: {Name:Bob Email:[email protected]}src := map[string]interface{}{
"Name": "Charlie",
"Age": 35,
"Email": "[email protected]",
}
type Destination struct {
Name string
Age int
Email string
}
dest := Destination{}
err := DeepCopy(&dest, src)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Destination: %+v\n", dest)
}
// Output: Destination: {Name:Charlie Age:35 Email:[email protected]}type Address struct {
City string
State string
}
type Source struct {
Name string
Age int
Address Address
}
type Destination struct {
Name string
Age int
Address Address
}
src := Source{
Name: "Bennett",
Age: 30,
Address: Address{
City: "New York",
State: "NY",
},
}
dest := Destination{}
err := DeepCopy(&dest, src)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Destination: %+v\n", dest)
}
// Output: Destination: {Name:Dave Age:40 Address:{City:New York State:NY}}- Purpose: Converts a byte size into a human-readable string (e.g., "1.23 MiB").
- Parameters:
bytes: The byte size to convert.
- Returns: A formatted string with the appropriate unit.
- Example:
result := ConvertBytes(1024 * 1024) fmt.Println(result) // Output: 1.00 MiB
- Purpose: Converts a string with a size suffix (e.g., "1M", "1Mi", "1MB") to bytes.
- Parameters:
input: The string to convert.
- Returns: The byte size or an error if the input is invalid.
- Example:
bytes, err := ConvertToBytes("1Mi") if err != nil { fmt.Println("Error:", err) } else { fmt.Println(bytes) // Output: 1048576 }
- Purpose: Parses a list of range strings (e.g.,
["1-3", "5"]) into a slice of integers. - Parameters:
rangeStrings: The list of range strings.
- Returns: A slice of integers or an error if parsing fails.
- Example:
result, err := ParseStringRanges([]string{"1-3", "5"}) if err != nil { fmt.Println("Error:", err) } else { fmt.Println(result) // Output: [1 2 3 5] }
- Purpose: Parses a single range string (e.g.,
"1-3") into a slice of integers. - Parameters:
rs: The range string.
- Returns: A slice of integers or an error if parsing fails.
- Example:
result, err := ParseStringRange("1-3") if err != nil { fmt.Println("Error:", err) } else { fmt.Println(result) // Output: [1 2 3] }
- Purpose: Parses a duration string (e.g.,
"1h30m") into atime.Duration. - Parameters:
durationStr: The duration string.
- Returns: A
time.Durationor an error if parsing fails. - Example:
duration, err := ParseDuration("1h30m") if err != nil { fmt.Println("Error:", err) } else { fmt.Println(duration) // Output: 1h30m0s }
- Purpose: Formats a duration into a human-readable string (e.g.,
"1.5s"). - Parameters:
d: The duration to format.decimalCount: The number of decimal places to include.
- Returns: A formatted string.
- Example:
result := FormatDuration(90*time.Second, 1) fmt.Println(result) // Output: 1.5m
- Purpose: Checks if the input string is a valid CIDR (Classless Inter-Domain Routing) notation.
- Parameters:
cidr: The string to validate as a CIDR.
- Returns:
trueif the input is a valid CIDR, otherwisefalse. - Example:
isValid := IsIPAddress("192.168.1.0/24") fmt.Println(isValid) // Output: true
- Purpose: Determines whether the input string is a valid IP address or a valid CIDR notation.
- Parameters:
input: The string to check.
- Returns:
isIP:trueif the input is a valid IP address.isCIDR:trueif the input is a valid CIDR notation.
- Example:
isIP, isCIDR := IsIPOrCIDR("192.168.1.1") fmt.Println(isIP, isCIDR) // Output: true, false isIP, isCIDR = IsIPOrCIDR("192.168.1.0/24") fmt.Println(isIP, isCIDR) // Output: false, true isIP, isCIDR = IsIPOrCIDR("invalid") fmt.Println(isIP, isCIDR) // Output: false, false
- Purpose: Checks if the input string is a valid IP address (IPv4 or IPv6).
- Parameters:
ip: The string to validate as an IP address.
- Returns:
trueif the input is a valid IP address, otherwisefalse. - Example:
isValid := IsIPAddress("192.168.1.1") fmt.Println(isValid) // Output: true isValid = IsIPAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334") fmt.Println(isValid) // Output: true isValid = IsIPAddress("invalid") fmt.Println(isValid) // Output: false
cidr := "192.168.1.0/24"
if IsCIDR(cidr) {
fmt.Println("Valid CIDR")
} else {
fmt.Println("Invalid CIDR")
}input := "192.168.1.1"
isIP, isCIDR := IsIPOrCIDR(input)
if isIP {
fmt.Println("Input is a valid IP address")
} else if isCIDR {
fmt.Println("Input is a valid CIDR")
} else {
fmt.Println("Input is neither an IP nor a CIDR")
}ip := "192.168.1.1"
if IsIPAddress(ip) {
fmt.Println("Valid IP address")
} else {
fmt.Println("Invalid IP address")
}- Purpose: Checks if a file exists at the specified path.
- Parameters:
filename: The path to the file.
- Returns:
trueif the file exists and is not a directory, otherwisefalse. - Example:
exists := FileExists("example.txt") fmt.Println(exists) // Output: true or false
- Purpose: Checks if a folder exists at the specified path.
- Parameters:
name: The path to the folder.
- Returns:
trueif the folder exists and is a directory, otherwisefalse. - Example:
exists := FolderExists("example_folder") fmt.Println(exists) // Output: true or false
- Purpose: Checks if a directory is empty.
- Parameters:
name: The path to the directory.
- Returns:
trueif the directory is empty, otherwisefalse. Returns an error if the directory cannot be accessed. - Example:
isEmpty, err := IsDirEmpty("example_folder") if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Is directory empty?", isEmpty) }
- Purpose: Copies a file from the source path to the destination path.
- Parameters:
src: The source file path.dst: The destination file path.
- Returns: An error if the operation fails.
- Example:
err := CopyFile("source.txt", "destination.txt") if err != nil { fmt.Println("Error:", err) } else { fmt.Println("File copied successfully!") }
- Purpose: Changes the file permissions of a file.
- Parameters:
filePath: The path to the file.mod: The permission mode (e.g.,0644).
- Returns: An error if the operation fails.
- Example:
err := ChangePermission("example.txt", 0644) if err != nil { fmt.Println("Error:", err) }
- Purpose: Writes content to a file at the specified path.
- Parameters:
filePath: The path to the file.content: The content to write.
- Returns: An error if the operation fails.
- Example:
err := WriteToFile("example.txt", "Hello, world!") if err != nil { fmt.Println("Error:", err) } else { fmt.Println("File written successfully!") }
- Purpose: Retrieves the value of an environment variable or returns a default value if the variable is not set.
- Parameters:
key: The environment variable key.defaultValue: The default value to return if the key is not set.
- Returns: The value of the environment variable or the default value.
- Example:
value := GetStringEnvWithDefault("MY_ENV_VAR", "default_value") fmt.Println(value) // Output: The value of MY_ENV_VAR or "default_value"
- Purpose: Retrieves the value of an environment variable as an integer or returns a default value if the variable is not set or invalid.
- Parameters:
key: The environment variable key.defaultValue: The default value to return if the key is not set or invalid.
- Returns: The integer value of the environment variable or the default value.
- Example:
value := GetIntEnv("MY_INT_ENV_VAR", 42) fmt.Println(value) // Output: The value of MY_INT_ENV_VAR or 42
- Purpose: Retrieves the value of an environment variable as a boolean or returns a default value if the variable is not set or invalid.
- Parameters:
key: The environment variable key.defaultValue: The default value to return if the key is not set or invalid.
- Returns: The boolean value of the environment variable or the default value.
- Example:
value := GetBoolEnv("MY_BOOL_ENV_VAR", true) fmt.Println(value) // Output: The value of MY_BOOL_ENV_VAR or true
- Purpose: Sets an environment variable.
- Parameters:
name: The environment variable name.value: The value to set.
- Example:
SetEnv("MY_ENV_VAR", "my_value")
- Purpose: Merges two slices of strings into one.
- Parameters:
slice1: The first slice.slice2: The second slice.
- Returns: A new slice containing all elements from
slice1andslice2. - Example:
result := MergeSlices([]string{"a", "b"}, []string{"c", "d"}) fmt.Println(result) // Output: [a b c d]
- Purpose: Normalizes a URL path by removing duplicate slashes and ensuring it starts with a single slash.
- Parameters:
urlPath: The URL path to normalize.
- Returns: The normalized URL path.
- Example:
path := ParseURLPath("//example//path//") fmt.Println(path) // Output: /example/path/
- Purpose: Checks if a string is valid JSON.
- Parameters:
s: The string to check.
- Returns:
trueif the string is valid JSON, otherwisefalse. - Example:
valid := IsJson(`{"key": "value"}`) fmt.Println(valid) // Output: true
- Purpose: Extracts the path from a URL.
- Parameters:
uri: The URL to parse.
- Returns: The path component of the URL.
- Example:
path := UrlParsePath("https://example.com/path") fmt.Println(path) // Output: /path
- Purpose: Checks if a string contains any whitespace.
- Parameters:
s: The string to check.
- Returns:
trueif the string contains whitespace, otherwisefalse. - Example:
hasSpace := HasWhitespace("hello world") fmt.Println(hasSpace) // Output: true
- Purpose: Converts a string into a URL-friendly slug.
- Parameters:
text: The string to convert.
- Returns: The slugified string.
- Example:
slug := Slug("Hello, World!") fmt.Println(slug) // Output: hello-world
- Purpose: Truncates a string to a specified length and appends "..." if truncated.
- Parameters:
text: The string to truncate.limit: The maximum length of the string.
- Returns: The truncated string.
- Example:
truncated := TruncateText("This is a long text", 10) fmt.Println(truncated) // Output: This is a...