Documentation ¶
Overview ¶
Package utils is a collection of useful, quickly accessible utility functions.
Index ¶
- func AppendToFile[T string | []byte](path string, content T) error
- func DownloadFile(url, path string) error
- func Fetch(url string) (string, error)
- func FileExists(path string) bool
- func PrettyJSON(inputJSON string, indent ...string) (string, error)
- func ReadFile(path string) (string, error)
- func Ternary[T any](condition bool, a, b T) T
- func ToInt[T string | constraints.Number](value T) int
- func ToJSON(v any) (string, error)
- func ToPrettyJSON(v any, indent ...string) (string, error)
- func ToString(v any) string
- func WriteFile[T string | []byte](path string, content T) error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AppendToFile ¶
AppendToFile appends the given content to the given file. Accepts a string or a byte slice.
func DownloadFile ¶
DownloadFile downloads the given URL to the given path. If the file already exists, it will be overwritten.
func FileExists ¶
FileExists returns true if the given file exists.
func PrettyJSON ¶
PrettyJSON returns a pretty-printed JSON string. If indent is not provided, it defaults to " " (two spaces).
Example ¶
person := Person{Name: "John Doe", Age: 42} json, _ := utils.ToJSON(person) prettyJSON, _ := utils.PrettyJSON(json) fmt.Println(prettyJSON)
Output: { "Name": "John Doe", "Age": 42 }
func Ternary ¶
Ternary is a ternary operator. It returns a if the condition is true, otherwise it returns b.
Example ¶
package main import ( "fmt" "atomicgo.dev/utils" ) func main() { fmt.Println(utils.Ternary(true, "a", "b")) fmt.Println(utils.Ternary(false, "a", "b")) }
Output: a b
func ToInt ¶
func ToInt[T string | constraints.Number](value T) int
ToInt converts the given value to an int. If the value is a float, it will be rounded to the nearest integer. (Rounds up if the decimal is 0.5 or higher)
Example ¶
package main import ( "fmt" "atomicgo.dev/utils" ) func main() { fmt.Println(utils.ToInt(1337)) fmt.Println(utils.ToInt(1337.4)) fmt.Println(utils.ToInt(1337.5)) fmt.Println(utils.ToInt(1337.6)) fmt.Println(utils.ToInt("1337")) fmt.Println(utils.ToInt("1337.4")) fmt.Println(utils.ToInt("1337.5")) fmt.Println(utils.ToInt("1337.6")) }
Output: 1337 1337 1338 1338 1337 1337 1338 1338
func ToJSON ¶
ToJSON converts the given value to a JSON string.
Example ¶
package main import ( "fmt" "atomicgo.dev/utils" ) type Person struct { Name string Age int } func main() { person := Person{"John Doe", 42} json, _ := utils.ToJSON(person) fmt.Println(json) }
Output: {"Name":"John Doe","Age":42}
func ToPrettyJSON ¶
Example ¶
package main import ( "fmt" "atomicgo.dev/utils" ) type Person struct { Name string Age int } func main() { person := Person{Name: "John Doe", Age: 42} prettyJSON, _ := utils.ToPrettyJSON(person) fmt.Println(prettyJSON) }
Output: { "Name": "John Doe", "Age": 42 }
Types ¶
This section is empty.