This document provides practical examples of how to use the library's features. Each section demonstrates a specific use case with clear, concise code snippets.
- Boolean
- Context (ctxutils)
- Error (errutils)
- Maps
- Pointers
- Random (rand)
- Slice
- Strings
- Structs
- Templates
- URLs
- Math
- Fake
- Time
- Loggin
package main
import (
"fmt"
boolutils "github.com/kashifkhan0771/utils/boolean"
)
func main() {
fmt.Println(boolutils.IsTrue("T"))
fmt.Println(boolutils.IsTrue("1"))
fmt.Println(boolutils.IsTrue("TRUE"))
}
true
true
true
package main
import (
"fmt"
boolutils "github.com/kashifkhan0771/utils/boolean"
)
func main() {
fmt.Println(boolutils.Toggle(true))
fmt.Println(boolutils.Toggle(false))
}
false
true
package main
import (
"fmt"
boolutils "github.com/kashifkhan0771/utils/boolean"
)
func main() {
fmt.Println(boolutils.AllTrue([]bool{true, true, true}))
fmt.Println(boolutils.AllTrue([]bool{true, false, true}))
fmt.Println(boolutils.AllTrue([]bool{}))
}
true
false
false
package main
import (
"fmt"
boolutils "github.com/kashifkhan0771/utils/boolean"
)
func main() {
fmt.Println(boolutils.AnyTrue([]bool{false, true, false}))
fmt.Println(boolutils.AnyTrue([]bool{false, false, false}))
fmt.Println(boolutils.AnyTrue([]bool{}))
}
true
false
false
package main
import (
"fmt"
boolutils "github.com/kashifkhan0771/utils/boolean"
)
func main() {
fmt.Println(boolutils.NoneTrue([]bool{false, false, false}))
fmt.Println(boolutils.NoneTrue([]bool{false, true, false}))
fmt.Println(boolutils.NoneTrue([]bool{}))
}
true
false
true
package main
import (
"fmt"
boolutils "github.com/kashifkhan0771/utils/boolean"
)
func main() {
fmt.Println(boolutils.CountTrue([]bool{true, false, true}))
fmt.Println(boolutils.CountTrue([]bool{false, false, false}))
fmt.Println(boolutils.CountTrue([]bool{}))
}
2
0
0
package main
import (
"fmt"
boolutils "github.com/kashifkhan0771/utils/boolean"
)
func main() {
fmt.Println(boolutils.CountFalse([]bool{true, false, true}))
fmt.Println(boolutils.CountFalse([]bool{false, false, false}))
fmt.Println(boolutils.CountFalse([]bool{}))
}
1
3
0
package main
import (
"fmt"
boolutils "github.com/kashifkhan0771/utils/boolean"
)
func main() {
fmt.Println(boolutils.Equal(true, true, true))
fmt.Println(boolutils.Equal(false, false, false))
fmt.Println(boolutils.Equal(true, false, true))
fmt.Println(boolutils.Equal())
}
true
true
false
false
package main
import (
"fmt"
boolutils "github.com/kashifkhan0771/utils/boolean"
)
func main() {
fmt.Println(boolutils.And([]bool{true, true, true}))
fmt.Println(boolutils.And([]bool{true, false, true}))
fmt.Println(boolutils.And([]bool{}))
}
true
false
false
package main
import (
"fmt"
boolutils "github.com/kashifkhan0771/utils/boolean"
)
func main() {
fmt.Println(boolutils.Or([]bool{false, true, false}))
fmt.Println(boolutils.Or([]bool{false, false, false}))
fmt.Println(boolutils.Or([]bool{}))
}
true
false
false
package main
import (
"context"
"fmt"
"github.com/kashifkhan0771/utils/ctxutils"
)
func main() {
// Create a context
ctx := context.Background()
// Set a string value in context
ctx = ctxutils.SetStringValue(ctx, ctxutils.ContextKeyString{"userName"}, "JohnDoe")
// Get the string value from context
userName, ok := ctxutils.GetStringValue(ctx, ctxutils.ContextKeyString{"userName"})
if ok {
fmt.Println(userName)
}
}
JohnDoe
package main
import (
"context"
"fmt"
"github.com/kashifkhan0771/utils/ctxutils"
)
func main() {
// Create a context
ctx := context.Background()
// Set an integer value in context
ctx = ctxutils.SetIntValue(ctx, ctxutils.ContextKeyInt{Key: 42}, 100)
// Get the integer value from context
value, ok := ctxutils.GetIntValue(ctx, ctxutils.ContextKeyInt{Key: 42})
if ok {
fmt.Println(value)
}
}
100
package main
import (
"fmt"
"errors"
"github.com/kashifkhan0771/utils/errutils"
)
func main() {
// Create a new error aggregator
agg := errutils.NewErrorAggregator()
// Add errors to the aggregator
agg.Add(errors.New("First error"))
agg.Add(errors.New("Second error"))
agg.Add(errors.New("Third error"))
// Retrieve the aggregated error
if err := agg.Error(); err != nil {
fmt.Println("Aggregated Error:", err)
}
}
Aggregated Error: First error; Second error; Third error
package main
import (
"fmt"
"errors"
"github.com/kashifkhan0771/utils/errutils"
)
func main() {
// Create a new error aggregator
agg := errutils.NewErrorAggregator()
// Add an error
agg.Add(errors.New("First error"))
// Check if there are any errors
if agg.HasErrors() {
fmt.Println("There are errors")
} else {
fmt.Println("No errors")
}
}
There are errors
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/maps"
)
func main() {
// Create a new StateMap
state := maps.NewStateMap()
// Set a state to true
state.SetState("isActive", true)
// Get the state
if state.IsState("isActive") {
fmt.Println("The state 'isActive' is true.")
} else {
fmt.Println("The state 'isActive' is false.")
}
}
The state 'isActive' is true.
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/maps"
)
func main() {
// Create a new StateMap
state := maps.NewStateMap()
// Set a state to true
state.SetState("isActive", true)
// Toggle the state
state.ToggleState("isActive")
// Check if the state is now false
if !state.IsState("isActive") {
fmt.Println("The state 'isActive' has been toggled to false.")
}
}
The state 'isActive' has been toggled to false.
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/maps"
)
func main() {
// Create a new StateMap
state := maps.NewStateMap()
// Set some states
state.SetState("isActive", true)
state.SetState("isVerified", false)
// Check if the state exists
if state.HasState("isVerified") {
fmt.Println("State 'isVerified' exists.")
} else {
fmt.Println("State 'isVerified' does not exist.")
}
}
State 'isVerified' exists.
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/maps"
)
func main() {
// Create a new Metadata map
meta := maps.NewMetadata()
// Update metadata with key-value pairs
meta.Update("author", "John Doe")
meta.Update("version", "1.0.0")
// Retrieve metadata values
fmt.Println("Author:", meta.Value("author"))
fmt.Println("Version:", meta.Value("version"))
}
Author: John Doe
Version: 1.0.0
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/maps"
)
func main() {
// Create a new Metadata map
meta := maps.NewMetadata()
// Update metadata with key-value pairs
meta.Update("author", "John Doe")
// Check if the key exists
if meta.Has("author") {
fmt.Println("Key 'author' exists.")
} else {
fmt.Println("Key 'author' does not exist.")
}
// Check for a non-existent key
if meta.Has("publisher") {
fmt.Println("Key 'publisher' exists.")
} else {
fmt.Println("Key 'publisher' does not exist.")
}
}
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/pointers"
)
func main() {
// Example of DefaultIfNil for a string pointer
var str *string
defaultStr := "Default String"
result := pointers.DefaultIfNil(str, defaultStr)
fmt.Println(result)
}
Default String
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/pointers"
)
func main() {
// Example of NullableBool for a bool pointer
var flag *bool
result := pointers.NullableBool(flag)
fmt.Println(result)
}
false
package main
import (
"fmt"
"time"
"github.com/kashifkhan0771/utils/pointers"
)
func main() {
// Example of NullableTime for a time.Time pointer
var t *time.Time
result := pointers.NullableTime(t)
fmt.Println(result)
}
0001-01-01 00:00:00 +0000 UTC
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/pointers"
)
func main() {
// Example of NullableInt for an int pointer
var num *int
result := pointers.NullableInt(num)
fmt.Println(result)
}
0
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/pointers"
)
func main() {
// Example of NullableString for a string pointer
var str *string
result := pointers.NullableString(str)
fmt.Println(result) // Output: ""
}
""
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/rand"
)
func main() {
num, err := rand.Number()
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Random Number:", num)
}
Random Number: 8507643814357583841
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/rand"
)
func main() {
num, err := rand.NumberInRange(10, 50)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Random Number in Range [10, 50]:", num)
}
Random Number in Range [10, 50]: 37
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/rand"
)
func main() {
str, err := rand.String()
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Random String:", str)
}
Random String: b5fG8TkWz1
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/rand"
)
func main() {
str, err := rand.StringWithLength(15)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Random String (Length 15):", str)
}
Random String (Length 15): J8fwkL2PvXM7NqZ
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/rand"
)
func main() {
charset := "abcdef12345"
str, err := rand.StringWithCharset(8, charset)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Random String with Custom Charset:", str)
}
Random String with Custom Charset: 1b2f3c4a
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/rand"
)
func main() {
words := []string{"apple", "banana", "cherry", "date", "elderberry"}
word, err := rand.Pick(words)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Random Word:", word)
}
Random Word: cherry
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/rand"
)
func main() {
numbers := []int{10, 20, 30, 40, 50}
num, err := rand.Pick(numbers)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Random Number:", num)
}
Random Number: 40
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/rand"
)
func main() {
numbers := []int{1, 2, 3, 4, 5}
err := rand.Shuffle(numbers)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Shuffled Numbers:", numbers)
}
Shuffled Numbers: [3 1 5 4 2]
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/rand"
)
func main() {
words := []string{"alpha", "beta", "gamma", "delta"}
err := rand.Shuffle(words)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Shuffled Words:", words)
}
Shuffled Words: [delta alpha gamma beta]
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/slice"
)
func main() {
strings := []string{"apple", "banana", "apple", "cherry", "banana", "date"}
uniqueStrings := slice.RemoveDuplicateStr(strings)
fmt.Println("Unique Strings:", uniqueStrings)
}
Unique Strings: [apple banana cherry date]
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/slice"
)
func main() {
numbers := []int{1, 2, 3, 2, 1, 4, 5, 3, 4}
uniqueNumbers := slice.RemoveDuplicateInt(numbers)
fmt.Println("Unique Numbers:", uniqueNumbers)
}
Unique Numbers: [1 2 3 4 5]
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/strings"
)
func main() {
options := strings.SubstringSearchOptions{
CaseInsensitive: true,
ReturnIndexes: false,
}
result := strings.SubstringSearch("Go is Great, Go is Fun!", "go", options)
fmt.Println(result) // Output: [Go Go]
}
func main() {
title := strings.Title("hello world")
fmt.Println(title) // Output: Hello World
}
func main() {
title := strings.ToTitle("hello world of go", []string{"of", "go"})
fmt.Println(title) // Output: Hello World of go
}
func main() {
tokens := strings.Tokenize("hello,world;this is Go", ",;")
fmt.Println(tokens) // Output: [hello world this is Go]
}
func main() {
encoded := strings.Rot13Encode("hello")
fmt.Println(encoded) // Output: uryyb
}
func main() {
decoded := strings.Rot13Decode("uryyb")
fmt.Println(decoded) // Output: hello
}
func main() {
encrypted := strings.CaesarEncrypt("hello", 3)
fmt.Println(encrypted) // Output: khoor
}
func main() {
decrypted := strings.CaesarDecrypt("khoor", 3)
fmt.Println(decrypted) // Output: hello
}
func main() {
encoded := strings.RunLengthEncode("aaabbbccc")
fmt.Println(encoded) // Output: 3a3b3c
}
func main() {
decoded, _ := strings.RunLengthDecode("3a3b3c")
fmt.Println(decoded) // Output: aaabbbccc
}
func main() {
valid := strings.IsValidEmail("test@example.com")
fmt.Println(valid) // Output: true
}
func main() {
email := strings.SanitizeEmail(" test@example.com ")
fmt.Println(email) // Output: test@example.com
}
func main() {
reversed := strings.Reverse("hello")
fmt.Println(reversed) // Output: olleh
}
func main() {
prefix := strings.CommonPrefix("nation", "national", "nasty")
fmt.Println(prefix) // Output: na
}
func main() {
suffix := strings.CommonSuffix("testing", "running", "jumping")
fmt.Println(suffix) // Output: ing
}
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/structs"
)
// Define a struct with fields tagged as `updateable`.
type User struct {
ID int `updateable:"false"` // Not updateable
Name string `updateable:"true"` // Updateable, uses default field name
Email string `updateable:"email_field"` // Updateable, uses a custom tag name
Age int `updateable:"true"` // Updateable, uses default field name
IsAdmin bool // Not tagged, so not updateable
}
func main() {
oldUser := User{
ID: 1,
Name: "Alice",
Email: "alice@example.com",
Age: 25,
IsAdmin: false,
}
newUser := User{
ID: 1,
Name: "Alice Johnson",
Email: "alice.johnson@example.com",
Age: 26,
IsAdmin: true,
}
// Compare the two struct instances.
results, err := structs.CompareStructs(oldUser, newUser)
if err != nil {
fmt.Println("Error:", err)
return
}
// Print the results.
for _, result := range results {
fmt.Printf("Field: %s, Old Value: %v, New Value: %v\n", result.FieldName, result.OldValue, result.NewValue)
}
}
Field: Name, Old Value: Alice, New Value: Alice Johnson
Field: email_field, Old Value: alice@example.com, New Value: alice.johnson@example.com
Field: Age, Old Value: 25, New Value: 26
package main
import (
"fmt"
"time"
"github.com/kashifkhan0771/utils/templates"
)
func main() {
// Define a sample HTML template
htmlTmpl := `
<!DOCTYPE html>
<html>
<head><title>{{ title .Title }}</title></head>
<body>
<h1>{{ toUpper .Header }}</h1>
<p>{{ .Content }}</p>
<p>Generated at: {{ formatDate .GeneratedAt "2006-01-02 15:04:05" }}</p>
</body>
</html>
`
// Define data for the HTML template
htmlData := map[string]interface{}{
"Title": "template rendering demo",
"Header": "welcome to the demo",
"Content": "This is a demonstration of the RenderHTMLTemplate function.",
"GeneratedAt": time.Now(),
}
// Render the HTML template
renderedHTML, err := templates.RenderHTMLTemplate(htmlTmpl, htmlData)
if err != nil {
fmt.Println("Error rendering HTML template:", err)
return
}
fmt.Println("Rendered HTML Template:")
fmt.Println(renderedHTML)
// Define a sample text template
textTmpl := `
Welcome, {{ toUpper .Name }}!
Today is {{ formatDate .Date "Monday, January 2, 2006" }}.
{{ if contains .Message "special" }}
Note: You have a special message!
{{ end }}
`
// Define data for the text template
textData := map[string]interface{}{
"Name": "Alice",
"Date": time.Now(),
"Message": "This is a special announcement.",
}
// Render the text template
renderedText, err := templates.RenderText(textTmpl, textData)
if err != nil {
fmt.Println("Error rendering text template:", err)
return
}
fmt.Println("Rendered Text Template:")
fmt.Println(renderedText)
}
<!DOCTYPE html>
<html>
<head><title>Template Rendering Demo</title></head>
<body>
<h1>WELCOME TO THE DEMO</h1>
<p>This is a demonstration of the RenderHTMLTemplate function.</p>
<p>Generated at: 2024-11-19 14:45:00</p>
</body>
</html>
Welcome, ALICE!
Today is Tuesday, November 19, 2024.
Note: You have a special message!
Here's a list of all available custom functions from the customFuncsMap
:
toUpper
: Converts a string to uppercase.toLower
: Converts a string to lowercase.title
: Converts a string to title case (e.g., "hello world" → "Hello World").contains
: Checks if a string contains a specified substring.replace
: Replaces all occurrences of a substring with another string.trim
: Removes leading and trailing whitespace from a string.split
: Splits a string into a slice based on a specified delimiter.reverse
: Reverses a string (supports Unicode characters).toString
: Converts a value of any type to its string representation.
formatDate
: Formats atime.Time
object using a custom layout.now
: Returns the current date and time (time.Time
).
add
: Adds two integers.sub
: Subtracts the second integer from the first.mul
: Multiplies two integers.div
: Divides the first integer by the second (integer division).mod
: Returns the remainder of dividing the first integer by the second.
isNil
: Checks if a value isnil
.not
: Negates a boolean value (e.g.,true
→false
).
dump
: Returns a detailed string representation of a value (useful for debugging).typeOf
: Returns the type of a value as a string.
safeHTML
: Marks a string as safe HTML, preventing escaping in templates.
url, err := BuildURL("https", "example.com", "search", map[string]string{"q": "golang"})
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("URL:", url)
}
// Output: https://example.com/search?q=golang
url, err := AddQueryParams("http://example.com", map[string]string{"key": "value", "page": "2"})
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Updated URL:", url)
}
// Output: http://example.com?key=value&page=2
isValid := IsValidURL("https://example.com", []string{"http", "https"})
fmt.Println("Is Valid:", isValid)
// Output: true
domain, err := ExtractDomain("https://sub.example.com/path?query=value")
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Domain:", domain)
}
// Output: example.com
value, err := GetQueryParam("https://example.com?foo=bar&baz=qux", "foo")
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Value:", value)
}
// Output: bar
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
fmt.Println(utils.Abs(-5))
fmt.Println(utils.Abs(10))
fmt.Println(utils.Abs(0))
}
5
10
0
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
fmt.Println(utils.Sign(15)) // Positive number
fmt.Println(utils.Sign(-10)) // Negative number
fmt.Println(utils.Sign(0)) // Zero
}
1
-1
0
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
fmt.Println(utils.Min(10, 20))
fmt.Println(utils.Min(25, 15))
fmt.Println(utils.Min(7, 7))
}
10
15
7
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
fmt.Println(utils.Max(10, 20))
fmt.Println(utils.Max(25, 15))
fmt.Println(utils.Max(7, 7))
}
20
25
7
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
fmt.Println(utils.Clamp(1, 10, 5)) // Value within range
fmt.Println(utils.Clamp(1, 10, 0)) // Value below range
fmt.Println(utils.Clamp(1, 10, 15)) // Value above range
}
5
1
10
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
fmt.Println(utils.IntPow(2, 3)) // 2^3
fmt.Println(utils.IntPow(5, 0)) // 5^0
fmt.Println(utils.IntPow(3, 2)) // 3^2
fmt.Println(utils.IntPow(2, -3)) // 3^(-3)
}
8
1
9
0.125
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
fmt.Println(utils.IsEven(8)) // Even number
fmt.Println(utils.IsEven(7)) // Odd number
fmt.Println(utils.IsEven(0)) // Zero
}
true
false
true
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
fmt.Println(utils.IsOdd(7)) // Odd number
fmt.Println(utils.IsOdd(8)) // Even number
fmt.Println(utils.IsOdd(0)) // Zero
}
true
false
false
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
x, y := 10, 20
utils.Swap(&x, &y)
fmt.Println(x, y)
}
20 10
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
result, err := utils.Factorial(5)
if err != nil {
fmt.Printf("%v\n", err)
}
fmt.Println(result)
}
120
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
fmt.Println(utils.GCD(12, 18))
fmt.Println(utils.GCD(17, 19)) // Prime numbers
fmt.Println(utils.GCD(0, 5)) // Zero input
}
6
1
5
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/math"
)
func main() {
fmt.Println(utils.LCM(4, 6))
fmt.Println(utils.LCM(7, 13)) // Prime numbers
fmt.Println(utils.LCM(0, 5)) // Zero input
}
12
91
0
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/fake"
)
func main() {
uuid, err := fake.RandomUUID()
if err != nil {
fmt.Println(err)
}
fmt.Println(uuid)
}
93a540eb-46e4-4e52-b0d5-cb63a7c361f9
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/fake"
)
func main() {
date, err := fake.RandomDate()
if err != nil {
fmt.Println(err)
}
fmt.Println(date)
}
2006-06-13 21:31:17.312528419 +0200 CEST
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/fake"
)
func main() {
num, err := fake.RandomPhoneNumber()
if err != nil {
fmt.Println(err)
}
fmt.Println(num)
}
+1 (965) 419-5534
package main
import (
"fmt"
"github.com/kashifkhan0771/utils/fake"
)
func main() {
address, err := fake.RandomAddress()
if err != nil {
fmt.Println(err)
}
fmt.Println(address)
}
81 Broadway, Rivertown, CT 12345, USA
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
t := time.Now()
fmt.Println(utils.StartOfDay(t))
}
2024-12-29 00:00:00 +0500 PKT
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
t := time.Now()
fmt.Println(utils.EndOfDay(t))
}
2024-12-29 23:59:59.999999999 +0500 PKT
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
t := time.Date(2024, 12, 27, 0, 0, 0, 0, time.Local) // Friday
// Add 3 business days
result := utils.AddBusinessDays(t, 3)
fmt.Println(result)
}
2025-01-01 00:00:00 +0500 PKT
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
saturday := time.Date(2024, 12, 28, 0, 0, 0, 0, time.Local)
monday := time.Date(2024, 12, 30, 0, 0, 0, 0, time.Local)
fmt.Printf("Is Saturday a weekend? %v\n", utils.IsWeekend(saturday))
fmt.Printf("Is Monday a weekend? %v\n", utils.IsWeekend(monday))
}
Is Saturday a weekend? true
Is Monday a weekend? false
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
now := time.Now()
future := now.Add(72 * time.Hour)
past := now.Add(-48 * time.Hour)
fmt.Println(utils.TimeDifferenceHumanReadable(now, future))
fmt.Println(utils.TimeDifferenceHumanReadable(now, past))
}
in 3 day(s)
2 day(s) ago
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
now := time.Now()
nextMonday := utils.DurationUntilNext(time.Monday, now)
fmt.Printf("Duration until next Monday: %v\n", nextMonday)
}
Duration until next Monday: 24h0m0s
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
t := time.Now()
nyTime, err := utils.ConvertToTimeZone(t, "America/New_York")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(nyTime)
}
2024-12-29 14:00:00 -0500 EST
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
d := 3*time.Hour + 25*time.Minute + 45*time.Second
fmt.Println(utils.HumanReadableDuration(d))
}
3h 25m 45s
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
birthDate := time.Date(1990, 5, 15, 0, 0, 0, 0, time.Local)
age := utils.CalculateAge(birthDate)
fmt.Printf("Age: %d years\n", age)
}
Age: 34 years
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
fmt.Printf("Is 2024 a leap year? %v\n", utils.IsLeapYear(2024))
fmt.Printf("Is 2023 a leap year? %v\n", utils.IsLeapYear(2023))
}
Is 2024 a leap year? true
Is 2023 a leap year? false
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
now := time.Now()
nextNoon := utils.NextOccurrence(12, 0, 0, now)
fmt.Println("Next noon:", nextNoon)
}
Next noon: 2024-12-30 12:00:00 +0500 PKT
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
t := time.Now()
year, week := utils.WeekNumber(t)
fmt.Printf("Year: %d, Week: %d\n", year, week)
}
Year: 2024, Week: 52
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
start := time.Date(2024, 1, 1, 0, 0, 0, 0, time.Local)
end := time.Date(2024, 12, 31, 0, 0, 0, 0, time.Local)
days := utils.DaysBetween(start, end)
fmt.Printf("Days between: %d\n", days)
}
Days between: 365
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
now := time.Now()
start := now.Add(-1 * time.Hour)
end := now.Add(1 * time.Hour)
fmt.Printf("Is current time between? %v\n", utils.IsTimeBetween(now, start, end))
}
Is current time between? true
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
ms := int64(1703836800000) // 2024-12-29 00:00:00
t := utils.UnixMilliToTime(ms)
fmt.Println(t)
}
2024-12-29 00:00:00 +0000 UTC
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
d := 50*time.Hour + 30*time.Minute + 15*time.Second
days, hours, minutes, seconds := utils.SplitDuration(d)
fmt.Printf("Days: %d, Hours: %d, Minutes: %d, Seconds: %d\n",
days, hours, minutes, seconds)
}
Days: 2, Hours: 2, Minutes: 30, Seconds: 15
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
monthName, err := utils.GetMonthName(12)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Month 12 is: %s\n", monthName)
}
Month 12 is: December
package main
import (
"fmt"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
dayName, err := utils.GetDayName(1)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Day 1 is: %s\n", dayName)
}
Day 1 is: Monday
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
t := time.Now()
formatted := utils.FormatForDisplay(t)
fmt.Println(formatted)
}
Sunday, 29 Dec 2024
package main
import (
"fmt"
"time"
utils "github.com/kashifkhan0771/utils/time"
)
func main() {
now := time.Now()
tomorrow := now.AddDate(0, 0, 1)
fmt.Printf("Is now today? %v\n", utils.IsToday(now))
fmt.Printf("Is tomorrow today? %v\n", utils.IsToday(tomorrow))
}
Is now today? true
Is tomorrow today? false
package main
import (
logging "github.com/kashifkhan0771/utils/logging"
"os"
)
func main() {
// Create a new logger with prefix "MyApp", minimum level INFO, and output to stdout
logger := logging.NewLogger("MyApp", logging.INFO, os.Stdout)
// Log messages of different levels
logger.Debug("This is a debug message.") // Ignored because minLevel is INFO
logger.Info("Application started.") // Printed with blue color
logger.Warn("Low disk space.") // Printed with yellow color
logger.Error("Failed to connect to DB.") // Printed with red color
}
[2025-01-09 12:34:56] [INFO] MyApp: Application started.
[2025-01-09 12:34:56] [WARN] MyApp: Low disk space.
[2025-01-09 12:34:56] [ERROR] MyApp: Failed to connect to DB.
package main
import (
logging "github.com/kashifkhan0771/utils/logging"
"os"
)
func main() {
// Create a logger and disable colors
logger := logging.NewLogger("MyApp", logging.DEBUG, os.Stdout)
logger.disableColors = true
// Log messages of different levels
logger.Debug("Debugging without colors.")
logger.Info("Information without colors.")
logger.Warn("Warning without colors.")
logger.Error("Error without colors.")
}
[2025-01-09 12:34:56] [DEBUG] MyApp: Debugging without colors.
[2025-01-09 12:34:56] [INFO] MyApp: Information without colors.
[2025-01-09 12:34:56] [WARN] MyApp: Warning without colors.
[2025-01-09 12:34:56] [ERROR] MyApp: Error without colors.
package main
import (
logging "github.com/kashifkhan0771/utils/logging"
"os"
)
func main() {
// Open a log file for writing
file, err := os.Create("app.log")
if err != nil {
panic(err)
}
defer file.Close()
// Create a logger with file output
logger := logging.NewLogger("MyApp", logging.DEBUG, file)
// Log messages
logger.Debug("Writing debug logs to file.")
logger.Info("Application log stored in file.")
logger.Warn("This is a warning.")
logger.Error("This is an error.")
}
[2025-01-09 12:34:56] [DEBUG] MyApp: Writing debug logs to file.
[2025-01-09 12:34:56] [INFO] MyApp: Application log stored in file.
[2025-01-09 12:34:56] [WARN] MyApp: This is a warning.
[2025-01-09 12:34:56] [ERROR] MyApp: This is an error.
package main
import (
logging "github.com/kashifkhan0771/utils/logging"
"os"
)
func main() {
// Create a logger with minimum level WARN
logger := logging.NewLogger("MyApp", logging.WARN, os.Stdout)
// Log messages
logger.Debug("This is a debug message.") // Ignored
logger.Info("This is an info message.") // Ignored
logger.Warn("This is a warning.") // Printed
logger.Error("This is an error.") // Printed
}
[2025-01-09 12:34:56] [WARN] MyApp: This is a warning.
[2025-01-09 12:34:56] [ERROR] MyApp: This is an error.
package main
import (
logging "github.com/kashifkhan0771/utils/logging"
"os"
)
func main() {
// Create a logger with a custom prefix
logger := logging.NewLogger("CustomPrefix", logging.INFO, os.Stdout)
// Log messages
logger.Info("This message has a custom prefix.")
}
[2025-01-09 12:34:56] [INFO] CustomPrefix: This message has a custom prefix.