gouse

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2025 License: MIT Imports: 71 Imported by: 3

README

ci_status sonar codacy DeepSource go_report_card codecov circleci go.dev documentation_website gouse_functions_count GitHub code size in bytes

Banner


Made possible by my Sponsor Program 💖

🧠 Why Gouse?

  • Gouse is a modern essentials Golang utility package delivering consistency, modularity, performance, and extras presets.
  • Built on top of Go language, and others Go open-source packages.
  • Inspired by Lodash so Javascript user-friendly syntax.
  • Lightweight package: easy to use, chainable, extendable, available.
  • Gouse provides a wide variety of available methods, taking the hassle out of working with any type requests. So you can pick the one of them that fit your project demands.
  • Powerful package of built-in functions provide comprehensive, and reliable solutions for any project size and compatible with all OS platforms.
  • Open-source, free to use, and contribute.

🎯 Features

  • Thanks to Gouse, you can:
    • Set up and scale projects rapidly.
    • No config - import directly as utility functions.
    • Handle complex logic use-cases such as database connection, build APIs, error handling, log management...
    • Optimize performance and increase productivity.
    • Build easily consistent systems with available functions.
    • Avoid writing repetitive code and a unified code style.
    • Reduce the number of lines of code and make it easier to read, understand, and maintain.
    • Avoid compatibility conflicts and unexpected errors.
    • Works smoothly in any environment and platform.
    • Easy to learn and use, suitable for beginners and experts.
    • Compatible with all frameworks and libraries.
    • Referencing examples with comprehensive documentation
    • And more...

✨ Motivation

  • Go has emerged as a server language, but it still doesn't have complete and consistent packages available to support coding development.
  • Developers must write by hand or search manually. That wastes time and even causes many compatibility conflicts.
  • Must update each dependent package every time when project update.
  • Unexpected errors can easily arise during execution.
  • Performance is not optimized.
  • The number of lines of code is very long that not easy to read and understand.
  • Code logic may not be consistent, making it difficult to maintain and scale.
  • Hard to make sure the programs are executed the same across all environments.
  • Lack of coherent learning materials and examples.

👉 To address that need, Gouse was created as a powerful presets toolkit for Go developers, a collection of built-in functions and best practices that provide comprehensive, powerful, and reliable solutions. Trusted to build services, software platforms, APIs, and web applications.

🚀 Module packages

Below is a list of modules that Gouse supports. This project is still in development stage, so not all features are available.

📋 Requirements

Compatibility with Go >= 1.18

📦 Installation

go get -u github.com/thuongtruong109/gouse

or add to your go.mod file:

required github.com/thuongtruong109/gouse

🕯️ Quick Start

package main

import "github.com/thuongtruong109/gouse"

func main() {
    gouse.Stater()
}

🦄 Usage

  • Using package directly in your module as ultra-lightweight utility functions.
package main

import "github.com/thuongtruong109/gouse"

func main() {
    gouse.Print(gouse.Add(1, 2))
}
  • View more examples at sample folder.

📖 Documentation

  • To read the completely package documentation guide, reference at Dev package

📊 Benchmark

GOOS: windows

GOARCH: amd64

CPU: AMD Ryzen 5 5600U with Radeon Graphics (12) @ 2.300GHz

ITERATIONS: 5

INPUT: 1000000

Benchmark

📁 Project Structure

Project Structure

🛠️ Development

$ git clone https://github.com/thuongtruong109/gouse.git

📝 Contributing

Gouse is an open source project and built on the top of other open-source projects. Welcome all the kinds of contributions. No matter it is for typo fix, bug fix or big new features. Please do not hesitate to ask a question or send a pull request.

We strongly value documentation and integration with other projects, so we are very glad to accept improvements for these aspects.

If you're looking for issues to work on, try looking at the good first issue list. We do our best to tag issues suitable for new external contributors with that label, so it's a great way to find something you can help with!

📄 License

📌 Support

  • The tool has been tested on a variety of inputs, but it's not perfect.
  • For support in using Gouse, please reach out in the following venues:
    • Raise Issues - For generally applicable issues and feedback.
    • Join Discussions - For ideas, questions, or issues regarding Gouse's design, development, and future.

📜 Changelog

  • Gouse is under active development. This means that new features, bug fixes, and breaking changes will be released frequently. We encourage you to keep the CHANGELOG open while upgrading to see what's new!

  • For more information on how to use the changelog, please refer to Keeping a Changelog.

🌸 Sponsor

  • If you like this project, you can sponsor me on:

Github sponsor Paypal Kofi

📮 Contact

  • If you have any questions, please contact me:

Email Github Linkedin Facebook

🧬 Dependencies

  • Gouse is built on top of the following below and others open-source projects

  • Special thanks to the following dependencies that helped make this project possible:

    • Google UUID - A fast and simple UUID library for Go 🔑
    • Survey v2 - A golang library for building interactive prompts with full support for windows and posix terminals 🙋
    • Bubbletea - A powerful little TUI framework 🏗
    • Go Cache - An in-memory key:value store/cache (similar to Memcached) 🗄
    • Crypto - A collection of cryptographic algorithms and protocols for Go 📦
    • Go eCharts - 🎨 The adorable charts library for Golang 📊
    • Env config x Go Toml - A Go library for managing configuration data from files 📄
    • Minio Client Go v7 - MinIO Go Library for Amazon S3 compatible cloud storage 📦
    • Mongodb Go driver - The MongoDB supported driver for Go 📦
    • Redis Go v8 - Type-safe Redis client for Golang 📦
    • Cache for Go - An in-memory key:value store/cache (similar to Memcached) library for Go 🗄
    • Toml Go - A Go library for managing configuration data from files 📄
    • Yaml - A YAML support for the Go language 📄

📚 References

Documentation

Index

Constants

View Source
const (
	INFO_LOG_PREFIX   string = "[INFO]"
	ERROR_LOG_PREFIX  string = "[ERROR]"
	ACCESS_LOG_PREFIX string = "[ACCESS]"
)
View Source
const (
	CHAIN_STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+{}[]|:<>?/.,';][=-`~"
	CHAIN_NUM = "0123456789"
)
View Source
const (
	ERROR_LOG_PATH  = "logs/error.log"
	INFO_LOG_PATH   = "logs/info.log"
	ACCESS_LOG_PATH = "logs/access.log"
)
View Source
const (
	DESC_TEST    = "Expected %v but it got %v"
	DESC_CONSOLE = "Unsupported action type"
)
View Source
const (
	// These maybe not supported by all terminals
	DEFAULT_CONSOLE string = "\033[0m"
	RED_CONSOLE     string = "\033[31m"
	GREEN_CONSOLE   string = "\033[32m"
	YELLOW_CONSOLE  string = "\033[33m"
	PURPLE_CONSOLE  string = "\033[34m"
	PINK_CONSOLE    string = "\033[35m"
	CYAN_CONSOLE    string = "\033[36m"
	WHITE_CONSOLE   string = "\033[97m"
	ORANGE_CONSOLE  string = "\033[38;5;208m"
	BLUE_CONSOLE    string = "\033[38;5;27m"
	MAGENTA_CONSOLE string = "\033[38;5;13m"
	GRAY_CONSOLE    string = "\033[37m"
)
View Source
const (
	// 	EmptyReg   = `^$`
	// 	SpaceReg   = `\s+`
	// 	WordNumReg = `^[a-zA-Z0-9]+$`
	UsernameReg = `^[a-zA-Z0-9_]{3,20}$`
	EmailLenReg = `^.{8,32}$`
	PhoneReg    = `^\+\d{1,2}\s?\(\d{1,4}\)\s?\d{1,6}-\d{1,6}$`

	PasswordLenReg     = `^.{8,32}$`
	PasswordLowerReg   = `[a-z]`
	PasswordUpperReg   = `[A-Z]`
	PasswordDigitReg   = `\d`
	PasswordSpecialReg = `[!@#$%^&*]`
)
View Source
const (
	DESC_CREATE_FAILED string = "create failed"
	DESC_GET_FAILED    string = "get failed"
	DESC_UPDATE_FAILED string = "update failed"
	DESC_DELETE_FAILED string = "delete failed"

	DESC_CREATE_SUCCESS string = "create successfully"
	DESC_GET_SUCCESS    string = "get successfully"
	DESC_UPDATE_SUCCESS string = "update successfully"
	DESC_DELETE_SUCCESS string = "delete successfully"

	DESC_NOT_FOUND_DATA string = "not found data"
	DESC_EMPTY_DATA     string = "empty data"
	DESC_INVALID_DATA   string = "invalid data"
)
View Source
const DefaultPageSize = 10

Variables

View Source
var (
	ErrorRequiredUuid error = errors.New("uuid is required")
	ErrorInvalidUuid  error = errors.New("uuid is invalid")

	ErrorInvalidEmail error = errors.New("email is invalid")
	ErrorEmailLength  error = errors.New("email must be between 8 and 32 characters long")

	ErrorInvalidUsername error = errors.New("username is invalid, must be between 3 and 20 characters long and only contains letters, numbers and underscore")

	ErrorInvalidPassword      error = errors.New("password is invalid, must be between 8 and 32 characters long and contains at least one lowercase letter, one uppercase letter, one digit and one special character")
	ErrorPasswordLength       error = errors.New("password must be between 8 and 32 characters long")
	ErrorPasswordEmptyLower   error = errors.New("password must contain at least one lowercase letter")
	ErrorPasswordEmptyUpper   error = errors.New("password must contain at least one uppercase letter")
	ErrorPasswordEmptyDigit   error = errors.New("password must contain at least one digit")
	ErrorPasswordEmptySpecial error = errors.New("password must contain at least one special character")

	ErrorHashPassword    error = errors.New("error when encrypt password")
	ErrorComparePassword error = errors.New("password not match")

	ErrorInvalidPhone error = errors.New("phone is invalid")
)
View Source
var DOUBLE_ALPHA = IFontDouble{
	`A`: {
		`╔═╗`,
		`╠═╣`,
		`╩ ╩`,
	},
	`B`: {
		`╔╗ `,
		`╠╩╗`,
		`╚═╝`,
	},
	`C`: {
		`╔═╗`,
		`║  `,
		`╚═╝`,
	},
	`D`: {
		`╦═╗`,
		`║ ║`,
		`╩═╝`,
	},
	`E`: {
		`╔═╗`,
		`║╣ `,
		`╚═╝`,
	},
	`F`: {
		`╔═╗`,
		`║╣ `,
		`╩  `,
	},
	`G`: {
		`╔═╗`,
		`║ ╦`,
		`╚═╝`,
	},
	`H`: {
		`╦ ╦`,
		`╠═╣`,
		`╩ ╩`,
	},
	`I`: {
		` ╦ `,
		` ║ `,
		` ╩ `,
	},
	`J`: {
		`╦═╦`,
		`  ║`,
		` ═╝`,
	},
	`K`: {
		`╦  ╦`,
		`╠═╔╝`,
		`╝ ╚`,
	},
	`L`: {
		`╦  `,
		`║  `,
		`╩═╝`,
	},
	`M`: {
		`╔╗╔╗`,
		`║║║║`,
		`╝╚╝╚`,
	},
	`N`: {
		`╔╗╔`,
		`║║║`,
		`╝╚╝`,
	},
	`O`: {
		`╔═╗`,
		`║ ║`,
		`╚═╝`,
	},
	`P`: {
		`╔═╗`,
		`╠═╝`,
		`╩  `,
	},
	`Q`: {
		`╔═╗`,
		`║ ║`,
		`╚═╚═`,
	},
	`R`: {
		`╔═╗`,
		`╠╔╝`,
		`╝╚╝`,
	},
	`S`: {
		`╔═╗`,
		`╚═╗`,
		`╚═╝`,
	},
	`T`: {
		`╔╦╗`,
		` ║ `,
		` ╩ `,
	},
	`U`: {
		`╦ ╦`,
		`║ ║`,
		`╚═╝`,
	},
	`V`: {
		`╦   ╦`,
		`╚╗ ╔╝`,
		` ╚╔╝`,
	},
	`W`: {
		`╦ ╦`,
		`║║║`,
		`╚╩╝`,
	},
	`X`: {
		`╚╔╝`,
		`╔╝╗`,
	},
	`Y`: {
		`╦ ╦`,
		`╚╔╝`,
		` ╩ `,
	},
	`Z`: {
		`╔═╗`,
		`╔═╝`,
		`╚═╝`,
	},
	`0`: {
		`╔═╗`,
		`║ ║`,
		`╚═╝`,
	},
	`1`: {
		` ╦ `,
		` ║ `,
		` ╩ `,
	},
	`2`: {
		`╔═╗`,
		`╔═╝`,
		`╚══`,
	},
	`3`: {
		`╔═╗`,
		`╚═╗`,
		`╚═╝`,
	},
	`4`: {
		`╦ ╦`,
		`╚═╣`,
		`  ╩`,
	},
	`5`: {
		`╔═╗`,
		`╚═╗`,
		`╚═╝`,
	},
	`6`: {
		`╔═╗`,
		`╠═╗`,
		`╚═╝`,
	},
	`7`: {
		`╔═╗`,
		` ═║`,
		`  ╩`,
	},
	`8`: {
		`╔═╗`,
		`╠═╣`,
		`╚═╝`,
	},
	`9`: {
		`╔═╗`,
		`╚═╣`,
		`╚═╝`,
	},
}

Functions

func Abs

func Abs(num int) int

func AbsF

func AbsF(num float64) float64

func Add

func Add[T int | float64](num1, num2 T) T

func AddStruct

func AddStruct(structInstance any, fields map[string]any) any

func AppendFile

func AppendFile(path string, data []string) error

func AreaCir added in v1.1.0

func AreaCir[T int | float64](radius T) float64

func AreaCone

func AreaCone[T Number](radius, height T) float64

func AreaCube

func AreaCube[T int | float64](side T) T

func AreaCyl added in v1.1.0

func AreaCyl[T Number](radius, height T) float64

func AreaEllipse

func AreaEllipse[T Number](major, minor T) float64

func AreaParallelogram

func AreaParallelogram[T int | float64](base, height T) T

func AreaPolygon

func AreaPolygon(lenSide float64, numSide int) float64

func AreaRect

func AreaRect[T int | float64](length, width T) T

func AreaRhombus

func AreaRhombus[T int | float64](diag1, diag2 T) T

func AreaSphere

func AreaSphere(radius int) float64

func AreaSphereF

func AreaSphereF(radius float64) float64

func AreaSquare

func AreaSquare[T int | float64](side T) T

func AreaTrapezoid

func AreaTrapezoid[T Number](base1, base2, height T) float64

func AreaTri added in v1.1.0

func AreaTri[T int | float64](base, height T) T

func At

func At(s string, index int) string
func Banner(font IFontDouble, s string)

func BarChart added in v1.1.0

func BarChart(options *IBarChart)

func Bool2Str added in v1.1.0

func Bool2Str(data bool) string

func Bytes2Str added in v1.1.0

func Bytes2Str(data []byte) string

func CamelCase

func CamelCase(s string) string

func Capitalize

func Capitalize(sentence string) string

func Cbrt

func Cbrt[T int | float64](number T) T

func Ceil

func Ceil(num float64) int

up to the nearest integer

func CheckPort

func CheckPort(protocol, hostname string, port int) bool

func CheckUrl added in v1.1.0

func CheckUrl(url string) (bool, int, error)

func Chunk

func Chunk[T comparable](array []T, size int) [][]T

func Clamp

func Clamp(value, min, max int) int

func CleanFile

func CleanFile(path string) error

func CloneStruct

func CloneStruct(structInstance any) any

func Cls

func Cls()

func Cmd

func Cmd(defaultCmd string, windowsCmd ...string)

func CodePoint

func CodePoint(input string) []int

func CodePointAt

func CodePointAt(s string, index int) int

func Compact

func Compact[T any](arr []T) []T

func ComparePassword added in v1.1.0

func ComparePassword(password, receivedPassword string) error

func ConTimeUrl added in v1.1.0

func ConTimeUrl(url string) (float64, error)

func Concat

func Concat(s ...string) string

func Confirm

func Confirm(label string) (bool, error)

func CopyFile

func CopyFile(oldPath, newPath string) error

func Cos

func Cos(angle int) float64

func CosF

func CosF(angle float64) float64

func Count

func Count(s string, substr ...string) int

func CreateCanvas

func CreateCanvas(size int, hexColor string) (*image.RGBA, error)

func CreateDir

func CreateDir(dir string) error

func CreateFile

func CreateFile(path string) error

func CreatePath

func CreatePath(relativePath string) error

func CtxCancel added in v1.1.0

func CtxCancel() (context.Context, context.CancelFunc)

func CurrentDir

func CurrentDir() (string, error)

func CustomCase

func CustomCase(s, sep string) string

func DashDate

func DashDate(date ...any) string

func Day

func Day() int

func DecodeData

func DecodeData(input []byte) ([]byte, error)

func DecodeUrl added in v1.1.0

func DecodeUrl(s string) string

func DecryptFile

func DecryptFile(source string, password []byte)

func DeferWrapper

func DeferWrapper(mainFunc func() error, cleanupFunc func()) error

func DetectErr added in v1.1.0

func DetectErr(err any) string

func DiagCube added in v1.1.0

func DiagCube(side int) float64

func DiagCubeF added in v1.1.0

func DiagCubeF(side float64) float64

func DiagRect

func DiagRect[T int | float64](length, width T) T

func DiagSquare added in v1.1.0

func DiagSquare[T Number](side T) float64

func Diff

func Diff[T comparable](a, b []T) []T

func DiffTime

func DiffTime(t1, t2 time.Time) time.Duration

func DiffTimeNow

func DiffTimeNow(startTime time.Time) time.Duration

func Distance

func Distance(speed, time float64) float64

func Div added in v1.1.0

func Div[T int | float64](num1, num2 T) T

func DotDate

func DotDate(date ...any) string

func Drop

func Drop[T comparable](arr []T, n ...int) []T

func EncodeData

func EncodeData(input []byte) ([]byte, error)

func EncodeUrl added in v1.1.0

func EncodeUrl(s string) string

func EncryptFile

func EncryptFile(source string, password []byte)

func EncryptPassword

func EncryptPassword(password string) (string, error)

func EndsWith

func EndsWith(s string, substr string) bool

func Equal

func Equal[T comparable](a, b []T) bool

func Err added in v1.1.0

func Err(err any) error

func ErrMsg added in v1.1.0

func ErrMsg(message string, err error) error

func Esc added in v1.1.0

func Esc(s string) string

func Extract added in v1.1.0

func Extract(zipFile, destFolder string) error

func Factorial

func Factorial(num int) int

func Fatal added in v1.1.0

func Fatal(msg error, err ...any)

func Fill added in v1.1.0

func Fill[T comparable](arr []T, value T, start, end int) []T

func FilterBy

func FilterBy[T comparable](arr []T, f func(T) bool) []T

func FindBy

func FindBy[T comparable](arr []T, f func(T) bool) T

func FirstIdx added in v1.1.0

func FirstIdx(s string, substr string) int

func Flatten added in v1.1.0

func Flatten(input any) []any

func Float2Str added in v1.1.0

func Float2Str(data float64) string

func Floor

func Floor(num float64) int

down to the nearest integer

func ForBy

func ForBy[T comparable](arr []T, f func(T))

func FromCodePoint

func FromCodePoint(codePoint ...int) string

func FromCodePointAt

func FromCodePointAt(codePoint int) string

func GetCtx

func GetCtx() context.Context

func GetStruct

func GetStruct(structInstance any, fieldName string) any

func GetTags added in v1.1.0

func GetTags(structInstance any) []string

func Go2Md

func Go2Md(inputPath, outputPath string)

func HasEmptyInStruct

func HasEmptyInStruct(structInstance any, fieldName string) bool

func HasInStruct

func HasInStruct(structInstance any, fieldName string) bool
func Header(w http.ResponseWriter, r *http.Request)

func HeaderUrl added in v1.1.0

func HeaderUrl(url string) (http.Header, error)

func HealthCheck

func HealthCheck()

func Help

func Help(name string, options []*IHelpOptions)

func Hex2Hlsa added in v1.1.0

func Hex2Hlsa(hex string) (float64, float64, float64, float64, error)

func Hex2Rgba added in v1.1.0

func Hex2Rgba(hex string) (color.RGBA, error)

func HierarchyDir

func HierarchyDir(dir string) ([]string, error)

func Hlsa2Rgba added in v1.1.0

func Hlsa2Rgba(h, l, s, a float64) color.RGBA

func Hour

func Hour() int

func Hue2Rgb added in v1.1.0

func Hue2Rgb(p, q, t float64) float64

func ISODate

func ISODate(date ...any) string

func IdxSubStr added in v1.1.0

func IdxSubStr(s, substr string) (int, int)

func InRange

func InRange(value, min, max int) bool

func Includes

func Includes(s string, substr string) bool

func IncludesArr

func IncludesArr[T comparable](array []T, value T) bool

func IndexBy

func IndexBy[T comparable](arr []T, f func(T) bool) int

func IndexOfArr

func IndexOfArr[T comparable](arr []T, value T) int

func Int2Str added in v1.1.0

func Int2Str(data int) string

func Intersect

func Intersect[T comparable](slices ...[]T) []T

func IntervalFunc

func IntervalFunc(fn func(), timeout int)

func IsArray

func IsArray(v any) bool

func IsBool

func IsBool(v any) bool

func IsByte

func IsByte(v any) bool

func IsChannel

func IsChannel(v any) bool

func IsComplex

func IsComplex(v any) bool

func IsDigit

func IsDigit[T byte | rune](char T) bool

func IsEdu

func IsEdu(emailStr string) (bool, error)

func IsEmail

func IsEmail(emailStr, customDomain string) (bool, error)

func IsEmpty

func IsEmpty(v any) bool

func IsEqualArr added in v1.1.0

func IsEqualArr[T comparable](a, b []T) bool

func IsError

func IsError(v any) bool

func IsEven

func IsEven(num int) bool

func IsExistDir

func IsExistDir(dir string) (bool, error)

func IsExistFile

func IsExistFile(path string) (bool, error)

func IsFloat

func IsFloat(v any) bool

func IsFunc

func IsFunc(v any) bool

func IsGmail

func IsGmail(emailStr string) (bool, error)

func IsInt

func IsInt(v any) bool

func IsLetter

func IsLetter[T byte | rune](char T) bool

func IsLower

func IsLower[T byte | rune](char T) bool

func IsMap

func IsMap(v any) bool

func IsMatchReg

func IsMatchReg(regex, chain string) bool

func IsNil

func IsNil(v any) bool

func IsNumber

func IsNumber(v any) bool

func IsOdd

func IsOdd(num int) bool

func IsOutlook

func IsOutlook(emailStr string) (bool, error)

func IsPassword

func IsPassword(password string) (bool, error)

func IsPerfectSquare

func IsPerfectSquare(num int) bool

func IsPhone

func IsPhone(phone string) (bool, error)

func IsPointer

func IsPointer(v any) bool

func IsPrime

func IsPrime(num int) bool

func IsRune

func IsRune(v any) bool

func IsSlice

func IsSlice(v any) bool

func IsString

func IsString(v any) bool

func IsStruct

func IsStruct(v any) bool

func IsUUID

func IsUUID(input string) (bool, error)

func IsUintptr

func IsUintptr(v any) bool

func IsUnInt

func IsUnInt(v any) bool

func IsUndefined

func IsUndefined(v any) bool

func IsUnsafePointer

func IsUnsafePointer(v any) bool

func IsUpper

func IsUpper[T byte | rune](char T) bool

func IsUsername

func IsUsername(username string) (bool, error)

func IsYahoo

func IsYahoo(emailStr string) (bool, error)

func IsZero

func IsZero(v any) bool

func Join

func Join(s []string, separator string) string

func KebabCase

func KebabCase(s string) string

func KeyBy

func KeyBy[T comparable](arr []T, f func(T) bool) int

func LPad added in v1.1.0

func LPad(s string, addAmount int, padChar byte) string

func LTrim

func LTrim(s string) string

func LastIdx added in v1.1.0

func LastIdx(s string, substr string) int

func Least added in v1.1.0

func Least[T comparable](arr []T) T

func LineChart added in v1.1.0

func LineChart(options *ILineChart)

func Lines

func Lines(s string) int

func LoadBalancer

func LoadBalancer(proxyPort string, backends []ILb)

func LockFunc

func LockFunc(callback any) any

func Log

func Log(number, base int) int

func Log10

func Log10(number int) int

func Log10F

func Log10F(number float64) float64

func Log2

func Log2(number int) int

func Log2F

func Log2F(number float64) float64

func LogF

func LogF(number, base float64) float64

func LongDate

func LongDate(date ...any) string

func Lower

func Lower[T byte | rune](char T) T

func LowerFirst

func LowerFirst(s string) string

func Lowers

func Lowers(s string) string

func LsDir

func LsDir(dir string) ([]string, error)

func Map2Str added in v1.1.0

func Map2Str[T string | []string](data map[string]T) string

func MapBy

func MapBy[T comparable, R comparable](arr []T, f func(T) R) []R

func MatchIdxReg added in v1.1.0

func MatchIdxReg(regex, chain string) int

func MatchReg

func MatchReg(regex, chain string) []string

func Max

func Max[T int | float64](nums ...T) T

func MaxArr

func MaxArr[T Number | string](arr []T) T

func Mean

func Mean[T int | float64](nums ...T) T

func Median added in v1.1.0

func Median[T int | float64](nums ...T) T

func Merge

func Merge[T comparable](arr ...[]T) []T

func MergeStruct

func MergeStruct(structs ...any) any

func Micro added in v1.1.0

func Micro() int64

func Micro2Time added in v1.1.0

func Micro2Time(micro int64) time.Time

func Milli added in v1.1.0

func Milli() int64

func Milli2Time added in v1.1.0

func Milli2Time(milli int64) time.Time

func Min

func Min[T int | float64](nums ...T) T

func MinArr

func MinArr[T Number | string](arr []T) T

func Minute

func Minute() int

func Mod added in v1.1.0

func Mod(num1, num2 int) int

func ModF added in v1.1.0

func ModF(num1, num2 float64) float64

func Mode added in v1.1.0

func Mode[T int | float64](nums ...T) T

func Mongo added in v1.1.0

func Mongo(ctx context.Context, uri string) (*mongo.Client, error)

func Month

func Month() int

func MonthDate

func MonthDate(date ...any) string

func Most

func Most[T comparable](arr []T) T

func Multi

func Multi[T int | float64](nums ...T) T

func Nano added in v1.1.0

func Nano() int64

func Nano2Time added in v1.1.0

func Nano2Time(nano int64) time.Time

func NormalDate

func NormalDate(date ...any) string

func OpenUrl added in v1.1.0

func OpenUrl(url string)

func OutputColor

func OutputColor[T any](color string, output T)

func OutputError

func OutputError(output string, err string)

func OutputSuccess

func OutputSuccess(output string)

func Panic added in v1.1.0

func Panic(msg error, err ...any)

func ParallelizeFunc

func ParallelizeFunc(functions ...func())

func PeriCir added in v1.1.0

func PeriCir[T int | float64](radius T) float64

func PeriCube

func PeriCube[T int | float64](side T) T

func PeriRect

func PeriRect[T int | float64](length, width T) T

func PeriSquare

func PeriSquare[T int | float64](side T) T

func PeriTri added in v1.1.0

func PeriTri[T int | float64](side1, side2, side3 T) T

func PieChart added in v1.1.0

func PieChart(options *IPieChart)

func Png2Jpg added in v1.1.0

func Png2Jpg(input, output string) error

func Pop added in v1.1.0

func Pop[T comparable](arr []T, n ...int) []T

func Pow

func Pow[T int | float64](base, exp T) T

func Pow2

func Pow2[T int | float64](base T) T

func Pow2F

func Pow2F(base float64) float64

func Pow3

func Pow3(base int) int

func Pow3F

func Pow3F(base float64) float64

func Print

func Print(args ...any)

func PrintUsage

func PrintUsage(name string, options []*IHelpOptions)

func Printf

func Printf(format string, args ...any)

func Println

func Println(args ...any)

func Profile

func Profile(cpuprofile, memprofile string)

func Proxy

func Proxy(port string, urls []string)

func Push added in v1.1.0

func Push[T comparable](arr []T, values ...T) []T

func Pytago

func Pytago[T int | float64](side1, side2 T) T

func RPad added in v1.1.0

func RPad(s string, addAmount int, padChar byte) string

func RTrim

func RTrim(s string) string

func RWLockFunc

func RWLockFunc(callback any) any

func RandDigit

func RandDigit(n int) string

func RandID

func RandID() string

func RandNum

func RandNum(min, max int) int

func RandStr

func RandStr(n int) string

func ReadFileByLine

func ReadFileByLine(path string) ([]string, error)

func ReadFileObj

func ReadFileObj[T any](path string) ([]T, error)

func ReadJSON

func ReadJSON[T any](path string, configuration *T) error

func ReadPath

func ReadPath(relativePath string) ([]byte, error)

func ReadTOML

func ReadTOML[T any](path string, configuration *T) error

func ReadYAML

func ReadYAML[T any](path string, configuration *T) error

func Redis added in v1.1.0

func Redis(addr, pass string, dbNo ...int) *redis.Client

func RedisCloud added in v1.1.0

func RedisCloud(uri string) *redis.Client

func RejectBy

func RejectBy[T comparable](arr []T, f func(T) bool) []T

func RemainFunc

func RemainFunc(fn func(), attempts int)

func RemoveDir

func RemoveDir(dir string) error

func RemoveFile

func RemoveFile(path string) error

func RenameFile

func RenameFile(oldPath, newPath string) error

func Repeat

func Repeat(s string, count int) string

func Replace

func Replace(s string, old string, new string) string

func RetryFunc

func RetryFunc(fn func() error, attempts int, sleep int) (err error)

func Reverse

func Reverse(s string) string

func ReverseArr added in v1.1.0

func ReverseArr[T comparable](arr []T) []T

func ReverseDate

func ReverseDate(date ...any) string

func Rgba2Hlsa added in v1.1.0

func Rgba2Hlsa(r, g, b, a uint8) (float64, float64, float64, float64)

func RmStruct added in v1.1.0

func RmStruct(structInstance any, fields ...string) any

func Root

func Root[T int | float64](number, n T) T

func RotateLog

func RotateLog(output string, maxFileSize ...int64)

func Round

func Round(num float64) int

round to the nearest integer

func RunJob

func RunJob(duration, stopAfter uint64, callback func())

func RunTimeFunc

func RunTimeFunc(startTime time.Time, task func()) time.Duration

func Rune2Str added in v1.1.0

func Rune2Str(data rune) string

func ScanPort

func ScanPort(protocol, hostname string, start, end int)

func ScatterChart added in v1.1.0

func ScatterChart(options *IScatterChart)

func Second

func Second() int

func Select

func Select(label string, options []string) (string, error)

func SetCtx

func SetCtx(ctx context.Context)

func SetStruct

func SetStruct(structInstance any, fieldName string, value any)

func Shift added in v1.1.0

func Shift[T comparable](arr []T, n ...int) []T

func Shuffle added in v1.1.0

func Shuffle[T comparable](arr []T)

func Sin

func Sin(angle int) float64

func SinF

func SinF(angle float64) float64

func SleepH added in v1.1.0

func SleepH(hour int)

func SleepM added in v1.1.0

func SleepM(minute int)

func SleepS added in v1.1.0

func SleepS(second int)

func Slice

func Slice(s string, index ...int) string

func SliceArr added in v1.1.0

func SliceArr[T comparable](arr []T, start, end int) ([]T, error)

func SnakeCase

func SnakeCase(s string) string

func Sort added in v1.1.0

func Sort(input any) any

func SortNum added in v1.1.0

func SortNum[T Number](nums []T) []T

func SpaceCase

func SpaceCase(s string) string

func SpaceDate

func SpaceDate(date ...any) string

func Speed

func Speed(distance, time float64) float64

func Splice

func Splice(s string, start, replaceCount int, items ...string) string

func SpliceArr added in v1.1.0

func SpliceArr[T comparable](arr []T, start, deleteCount int, items ...T) []T

func Split

func Split(s string, separator string) []string

func Sprint

func Sprint(args ...any) string

func Sprintf

func Sprintf(format string, args ...any) string

func Sprintln

func Sprintln(args ...any) string

func Sqrt

func Sqrt[T int | float64](number T) T

func Starter

func Starter()

func StartsWith

func StartsWith(s string, substr string) bool

func Str2Bool added in v1.1.0

func Str2Bool(data string) bool

func Str2Bytes added in v1.1.0

func Str2Bytes(data string) []byte

func Str2Float added in v1.1.0

func Str2Float(data string) float64

func Str2Int added in v1.1.0

func Str2Int(data string) int

func Strs2Bytes added in v1.1.0

func Strs2Bytes(data []string) []byte

func Struct2Map added in v1.1.0

func Struct2Map(data any) map[string]any

func Struct2Str added in v1.1.0

func Struct2Str(data any) string

func Sub

func Sub[T int | float64](num1, num2 T) T

func SubStr

func SubStr(s string, start int, length ...int) string

func Sum

func Sum[T int | float64](nums ...T) T

func Take added in v1.1.0

func Take[T comparable](arr []T, n int) []T

func Tan

func Tan(angle int) float64

func TanF

func TanF(angle float64) float64

func TerminalClock

func TerminalClock()

func Time

func Time(distance, speed float64) float64

func Time2Str added in v1.1.0

func Time2Str(t time.Time) string

func ToHour

func ToHour(hour int) time.Duration

func ToMinute

func ToMinute(minute int) time.Duration

func ToSecond

func ToSecond(second int) time.Duration

func ToStr added in v1.1.0

func ToStr(data any) string

func Trim

func Trim(s string) string

func TrimBlank

func TrimBlank(s string) string

func TrimPre added in v1.1.0

func TrimPre(s, prefix string) string

func TrimSuf added in v1.1.0

func TrimSuf(s, suffix string) string

func Truncate

func Truncate(s string, length int, omission ...string) string

func TruncateFile

func TruncateFile(path string, size int64) error

func UTCDate

func UTCDate(date ...any) string

func UUID

func UUID() string

func UnderlineDate

func UnderlineDate(date ...any) string

func Unesc added in v1.1.0

func Unesc(s string) string

func UniqueArr added in v1.1.0

func UniqueArr[T comparable](arr []T) []T

func Unix

func Unix() int64

func Unshift added in v1.1.0

func Unshift[T comparable](arr []T, values ...T) []T

func UploadMulti added in v1.1.0

func UploadMulti(w http.ResponseWriter, r *http.Request, servePath, storePath string)

func UploadSingle added in v1.1.0

func UploadSingle(w http.ResponseWriter, r *http.Request, servePath, storePath string)

func Upper

func Upper[T byte | rune](char T) T

func UpperFirst

func UpperFirst(s string) string

func Uppers

func Uppers(s string) string

func Validate added in v1.1.0

func Validate(ctxBind func() error, ctxReq func() context.Context, req any) error

func VolCone

func VolCone[T Number](radius, height T) float64

func VolCube

func VolCube(side int) int

func VolCubeF

func VolCubeF(side float64) float64

func VolCyl added in v1.1.0

func VolCyl[T Number](radius, height T) float64

func VolRect

func VolRect[T int | float64](length, width, height T) T

func VolSphere

func VolSphere(radius int) float64

func VolSphereF

func VolSphereF(radius float64) float64

func Weekday

func Weekday() int

func Words

func Words(s string) []string

func WriteAccessLog

func WriteAccessLog(msg string)

func WriteErrorLog

func WriteErrorLog(msg string, err any)

func WriteFile

func WriteFile(path string, data []string) error

func WriteFileObj

func WriteFileObj[T any](path string, data T) error

func WriteInfoLog

func WriteInfoLog(msg string)

func WriteLog

func WriteLog(prefix, msg, filePath string, err ...any)

func WriteLogDefault

func WriteLogDefault(logID, logMessage, output string)

func WritePath

func WritePath(relativePath string, content []byte) error

func Year

func Year() int

func Zip

func Zip(zipFileName string, files []string) error

Types

type DelayedResult

type DelayedResult[T any] struct {
	Value     T
	HasReturn bool
}

Delay

func DelayF

func DelayF[T any](f func() T, timeout int) DelayedResult[T]

func DelayFunc

func DelayFunc(f func(), timeout int) DelayedResult[struct{}]

type FileInfoStruct

type FileInfoStruct struct {
	Name    string
	Size    int64
	Mode    os.FileMode
	ModTime string
	IsDir   bool
	Sys     any
	All     os.FileInfo
}

func FileInfo

func FileInfo(path string) (*FileInfoStruct, error)

type Function

type Function struct {
	Import string
	Order  string
	Name   string
	Desc   string
	Body   string
}

func ExtractFunctions

func ExtractFunctions(code []byte) []Function

func (*Function) HighlightBody

func (f *Function) HighlightBody() string

func (*Function) HighlightDesc

func (f *Function) HighlightDesc() string

func (*Function) HighlightImport

func (f *Function) HighlightImport() string

func (*Function) HighlightName

func (f *Function) HighlightName() string

type IBarChart added in v1.1.0

type IBarChart struct {
	Output   string
	Title    string
	Subtitle string
	XAxis    []string
	Items    []IBarChartItem
}

type IBarChartItem

type IBarChartItem struct {
	Name   string
	Values []float64
}

type ICPU

type ICPU struct {
	CPU        int32
	Speed      string
	Cores      int
	VendorID   string
	Family     string
	Model      string
	Stepping   int32
	PhysicalID string
	CoreID     string
	ModelName  string
	Mhz        float64
	CacheSize  int32
	Flags      []string
	Microcode  string
}

func CPU

func CPU() (*ICPU, error)

type ICron added in v1.1.0

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

func NewCron added in v1.1.0

func NewCron(duration, stopAfter time.Duration, callback func()) *ICron

func (*ICron) StartJob added in v1.1.0

func (cj *ICron) StartJob()

func (*ICron) WaitJob added in v1.1.0

func (cj *ICron) WaitJob()

type IDisk

type IDisk struct {
	Path              string
	Fstype            string
	Total             uint64
	Free              uint64
	Used              uint64
	UsedPercent       float64
	InodesTotal       uint64
	InodesUsed        uint64
	InodesFree        uint64
	InodesUsedPercent float64
}

func Disk

func Disk() (*IDisk, error)

type IFontDouble added in v1.1.0

type IFontDouble map[string][3]string

type IHeader added in v1.1.0

type IHeader struct {
	Method        string
	Addr          string
	URL           string
	Proto         string
	Host          string
	StatusCode    int
	ContentLength int
	ContentType   string
}

type IHelpActionBool

type IHelpActionBool struct {
	Action func(bool)
}

type IHelpActionInt

type IHelpActionInt struct {
	Action func(int)
}

type IHelpActionStr

type IHelpActionStr struct {
	Action func(string)
}

type IHelpOptions

type IHelpOptions struct {
	Opt    string
	Desc   string
	Val    any
	Action any
}

type IHost added in v1.1.0

type IHost struct {
	Name                 string
	Platform             string
	Arch                 string
	Hostname             string
	NumsProcs            uint64
	Uptime               uint64
	BootTime             uint64
	Procs                uint64
	OS                   string
	PlatformFamily       string
	PlatformVersion      string
	KernelVersion        string
	KernelArch           string
	VirtualizationSystem string
	VirtualizationRole   string
	HostID               string
}

func Host added in v1.1.0

func Host() (*IHost, error)

type IIo added in v1.1.0

type IIo struct {
	ReadCount        uint64
	MergedReadCount  uint64
	WriteCount       uint64
	MergedWriteCount uint64
	ReadBytes        uint64
	WriteBytes       uint64
	ReadTime         uint64
	WriteTime        uint64
	IopsInProgress   uint64
	IoTime           uint64
	WeightedIO       uint64
	Name             string
	SerialNumber     string
	Label            string
}

func Io added in v1.1.0

func Io() ([]*IIo, error)

type ILCache added in v1.1.0

type ILCache struct {
	Set  map[string]string
	Lock sync.RWMutex
}

func NewLCache added in v1.1.0

func NewLCache() *ILCache

func (*ILCache) AllLCache added in v1.1.0

func (c *ILCache) AllLCache() map[string]string

func (*ILCache) DelLCache added in v1.1.0

func (c *ILCache) DelLCache(key string)

func (*ILCache) FlushLCache added in v1.1.0

func (c *ILCache) FlushLCache()

func (*ILCache) GetLCache added in v1.1.0

func (c *ILCache) GetLCache(key string) (string, error)

func (*ILCache) SetLCache added in v1.1.0

func (c *ILCache) SetLCache(key, value string)

type ILb added in v1.1.0

type ILb struct {
	URL    string `json:"url"`
	IsDead bool
	// contains filtered or unexported fields
}

func (*ILb) GetIsDead added in v1.1.0

func (backend *ILb) GetIsDead() bool

func (*ILb) SetDead added in v1.1.0

func (backend *ILb) SetDead(b bool)

type ILbConf added in v1.1.0

type ILbConf struct {
	ProxyPort string `json:"proxy"`
	Backends  []ILb  `json:"backends"`
}

type ILineChart added in v1.1.0

type ILineChart struct {
	Output   string
	Title    string
	Subtitle string
	XAxis    []string
	Items    []ILineChartItem
}

type ILineChartItem

type ILineChartItem struct {
	Name   string
	Values []float64
}

type ILog

type ILog struct {
	Prefix  string
	Message string
	Output  string
}

type IMemory added in v1.1.0

type IMemory struct {
	VirtualTotal          uint64
	VirtualAvailable      uint64
	VirtualUsed           uint64
	VirtualUsedPercent    float64
	VirtualFree           uint64
	VirtualActive         uint64
	VirtualInactive       uint64
	VirtualWired          uint64
	VirtualLaundry        uint64
	VirtualBuffers        uint64
	VirtualCached         uint64
	VirtualWriteBack      uint64
	VirtualDirty          uint64
	VirtualWriteBackTmp   uint64
	VirtualShared         uint64
	VirtualSlab           uint64
	VirtualSreclaimable   uint64
	VirtualSunreclaim     uint64
	VirtualPageTables     uint64
	VirtualSwapCached     uint64
	VirtualCommitLimit    uint64
	VirtualCommittedAS    uint64
	VirtualHighTotal      uint64
	VirtualHighFree       uint64
	VirtualLowTotal       uint64
	VirtualLowFree        uint64
	VirtualMapped         uint64
	VirtualMallocTotal    uint64
	VirtualMallocUsed     uint64
	VirtualMallocChunk    uint64
	VirtualHugePagesTotal uint64
	VirtualHugePagesFree  uint64
	VirtualHugePagesRsvd  uint64
	VirtualHugePagesSurp  uint64
	VirtualHugePageSize   uint64
	VirtualAnonHugePages  uint64

	SwapTotal       uint64
	SwapUsed        uint64
	SwapFree        uint64
	SwapUsedPercent float64
	SwapSin         uint64
	SwapSout        uint64
	SwapPgIn        uint64
	SwapPgOut       uint64
	SwapPgFault     uint64
	SwapPgMajFault  uint64
}

func Memory added in v1.1.0

func Memory() (*IMemory, error)

type IPartition added in v1.1.0

type IPartition struct {
	Device     string
	Mountpoint string
	Fstype     string
	Opts       []string
}

func Partition added in v1.1.0

func Partition() ([]*IPartition, error)

type IPieChart added in v1.1.0

type IPieChart struct {
	Output     string
	Title      string
	Subtitle   string
	Annotation string
	Radius     float64
	Format     string
	ShowLabel  bool
	Items      []IPieChartItem
}

type IPieChartItem

type IPieChartItem struct {
	Name   string
	Values float64
}

type IScatterChart added in v1.1.0

type IScatterChart struct {
	Output     string
	Title      string
	Subtitle   string
	Annotation string
	XAxis      []string
	Items      []float64
}

type IServer added in v1.1.0

type IServer struct {
	Port          string
	StartMsg      string
	ShutdownMsg   string
	SleepTimeout  time.Duration
	HeaderTimeout time.Duration
}

func (*IServer) Server added in v1.1.0

func (igs *IServer) Server()

type ITCache added in v1.1.0

type ITCache struct {
	Expires time.Duration
	Set     *cache.Cache
}

func NewTCache added in v1.1.0

func NewTCache(expires ...time.Duration) *ITCache

func (*ITCache) AllTCache added in v1.1.0

func (c *ITCache) AllTCache() map[string]string

func (*ITCache) DelTCache added in v1.1.0

func (c *ITCache) DelTCache(cacheKey string)

func (*ITCache) FlushTCache added in v1.1.0

func (c *ITCache) FlushTCache()

func (*ITCache) GetTCache added in v1.1.0

func (c *ITCache) GetTCache(cacheKey string) interface{}

func (*ITCache) SetTCache added in v1.1.0

func (c *ITCache) SetTCache(cacheKey string, value interface{}, expireTime time.Duration)

type ITest

type ITest struct {
	Name    string
	Input   string
	Want    bool
	WantErr bool
}

type IUser added in v1.1.0

type IUser struct {
	User     string
	Terminal string
	Host     string
	Started  int
}

func User added in v1.1.0

func User() ([]*IUser, error)

type Number added in v1.1.0

type Number interface {
	int | int8 | int16 | int32 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64
}

type Pagination added in v1.1.0

type Pagination struct {
	Size    int    // Items per page
	Page    int    // Current page
	OrderBy string // Sorting order (e.g., "asc", "desc")
	Total   int    // Total number of items available
}

func NewPagination added in v1.1.0

func NewPagination(size, page int) *Pagination

func (*Pagination) GetFirstPage added in v1.1.0

func (p *Pagination) GetFirstPage() int

func (*Pagination) GetHasMore added in v1.1.0

func (p *Pagination) GetHasMore(totalCount int) bool

func (*Pagination) GetLastPage added in v1.1.0

func (p *Pagination) GetLastPage() int

func (*Pagination) GetNextPage added in v1.1.0

func (p *Pagination) GetNextPage() int

func (*Pagination) GetOffset added in v1.1.0

func (p *Pagination) GetOffset() int

func (*Pagination) GetOrderBy added in v1.1.0

func (p *Pagination) GetOrderBy() string

func (*Pagination) GetPage added in v1.1.0

func (p *Pagination) GetPage() int

func (*Pagination) GetPrevPage added in v1.1.0

func (p *Pagination) GetPrevPage() int

func (*Pagination) GetQueryString added in v1.1.0

func (p *Pagination) GetQueryString() string

func (*Pagination) GetSize added in v1.1.0

func (p *Pagination) GetSize() int

func (*Pagination) GetTotalPages added in v1.1.0

func (p *Pagination) GetTotalPages() int

func (*Pagination) SetOrderBy added in v1.1.0

func (p *Pagination) SetOrderBy(orderByQuery string)

func (*Pagination) SetPage added in v1.1.0

func (p *Pagination) SetPage(pageQuery string) error

func (*Pagination) SetSize added in v1.1.0

func (p *Pagination) SetSize(sizeQuery string) error

type PgDB

type PgDB struct {
	Client *sql.DB
}

func Postgres added in v1.1.0

func Postgres(dsn string) (*PgDB, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳