goutil

package module
v4.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2023 License: MIT Imports: 24 Imported by: 2

README

Go Util

donation link

A simple utility package for golang.

This module simply adds a variety of useful functions in an easy to use way.

Installation


  go get github.com/AspieSoft/goutil/v4

Usage


import (
  "github.com/AspieSoft/goutil/v3"
)

func main(){
  goutil.JoinPath("root", "file") // a safer way to join 2 file paths without backtracking

  goutil.Contains([]any, any) // checks if an array contains a value

  // simple AES-CFB Encryption
  encrypted := goutil.Encrypt([]byte("my message"), []byte("password"))
  goutil.Decrypt(encrypted, []byte("password"))

  // simple gzip compression for strings
  compressed := goutil.Compress([]byte("my long string"))
  goutil.Decompress(compressed)

  // watch a directory recursively
  goutil.WatchDir("my/folder", &goutil.Watcher{
    FileChange: func(path string, op string){
      // do something when a file changes
      path // the file path the change happened to
      op // the change operation
    },

    DirAdd: func(path string, op string){
      // do something when a directory is added
      // return false to prevent that directory from being watched
      return true
    },

    Remove: func(path string, op string){
      // do something when a file or directory is removed
      // return false to prevent that directory from no longer being watched
      return true
    },

    Any: func(path string, op string){
      // do something every time something happenes
    },
  })
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var VarType map[string]reflect.Type

Functions

func BrotliCompress added in v4.1.0

func BrotliCompress(msg []byte, quality int) ([]byte, error)

BrotliCompress Compresses with brotli to a utf8 []byte

@quality 0-11 (0 = fastest) (11 = best)

func BrotliDecompress added in v4.1.0

func BrotliDecompress(b []byte) ([]byte, error)

BrotliCompress Decompresses with brotli from a utf8 []byte

func CleanArray

func CleanArray(data []interface{}) []interface{}

CleanArray runs `CleanStr` on an []interface{}

CleanStr sanitizes a string to valid UTF-8

func CleanByte

func CleanByte(b []byte) []byte

CleanByte will sanitizes a []byte to valid UTF-8

func CleanJSON

func CleanJSON(val interface{}) interface{}

CleanJSON runs `CleanStr` on a complex json object recursively

CleanStr sanitizes a string to valid UTF-8

func CleanMap

func CleanMap(data map[string]interface{}) map[string]interface{}

CleanMap runs `CleanStr` on a map[string]interface{}

CleanStr sanitizes a string to valid UTF-8

func CleanStr

func CleanStr(str string) string

CleanStr will sanitizes a string to valid UTF-8

func CloseWatchers

func CloseWatchers(root string)

CloseWatchers will close all the watchers with the given root if they were created by goutil

@root pass a file path for a specific watcher or "*" for all watchers that exist

note: this method may include other modules that are using goutil as a dependency

func CompareHash

func CompareHash(text []byte, compare []byte, key []byte) bool

CompareHash compares a key based hash created by the `NewHash` func to another text, to safely check for equality

uses HMAC with SHA256

the key is also hashed with SHA256

@compare should be a valid hash

func Compress

func Compress(msg []byte) ([]byte, error)

Compress is Gzip compression for a string

func Contains

func Contains[T any](search []T, value T) bool

Contains returns true if an array contains a value

func ContainsMap

func ContainsMap[T Hashable, J any](search map[T]J, value J) bool

ContainsMap returns true if a map contains a value

func ContainsMapKey

func ContainsMapKey[T Hashable, J any](search map[T]J, key T) bool

ContainsMapKey returns true if a map contains a key

func DecodeJSON

func DecodeJSON(data io.Reader) (map[string]interface{}, error)

DecodeJSON is useful for decoding a JSON output from the body of an http request

example: goutil.DecodeJSON(r.Body)

func Decompress

func Decompress(str []byte) ([]byte, error)

Decompress is Gzip decompression for a string

func Decrypt

func Decrypt(text []byte, key []byte) ([]byte, error)

Decrypt runs AES-CFB Decryption

the key is also hashed with SHA256

func DecryptLocal

func DecryptLocal(ciphertext []byte, key []byte) ([]byte, error)

DecryptLocal is a Non Standard AES-CFB Decryption method

Notice This Feature Is Experimental

purposely incompatible with other libraries and programing languages

this was made by accident, and this bug is now a feature

func DeepCopyJson

func DeepCopyJson(data map[string]interface{}) (map[string]interface{}, error)

DeepCopyJson will stringify and parse json to create a deep copy and escape pointers

func Encrypt

func Encrypt(text []byte, key []byte) ([]byte, error)

Encrypt runs AES-CFB Encryption

the key is also hashed with SHA256

func EncryptLocal

func EncryptLocal(text []byte, key []byte) ([]byte, error)

EncryptLocal is a Non Standard AES-CFB Encryption method

Notice This Feature Is Experimental

purposely incompatible with other libraries and programing languages

this was made by accident, and this bug is now a feature

func EscapeHTML

func EscapeHTML(html []byte) []byte

EscapeHTML replaces HTML characters with html entities

Also prevents and removes & from results

func EscapeHTMLArgs

func EscapeHTMLArgs(html []byte, quote ...byte) []byte

EscapeHTMLArgs escapes quotes and backslashes for use within HTML quotes @quote can be used to only escape specific quotes or chars

func FormatMemoryUsage

func FormatMemoryUsage(b uint64) float64

FormatMemoryUsage converts bytes to megabytes

func GetFileFromParent

func GetFileFromParent(root string, start string, search string) (string, bool)

GetFileFromParent checks if the parent (or sub parent) directory of a file contains a specific file or folder

@root is the highest grandparent to check before quitting

@start is the lowest level to start searching from (if a directory is passed, it will not be included in your search)

@search is what file you want to search fro

func GetLinuxInstaller

func GetLinuxInstaller(man []string) string

GetLinuxInstaller attempt to find out what package manager a linux distro is using or has available

func Gunzip added in v4.1.0

func Gunzip(b []byte) ([]byte, error)

Gunzip is Gzip decompression from a utf8 []byte

func Gzip added in v4.1.0

func Gzip(msg []byte) ([]byte, error)

Gzip is Gzip compression to a utf8 []byte

func HasLinuxPkg

func HasLinuxPkg(pkg []string) bool

HasLinuxPkg attempt to check if a linux package is installed

func IndexOf

func IndexOf[T any](search []T, value T) (int, error)

IndexOf returns the index of a value in an array

returns -1 and an error if the value is not found

func IndexOfMap

func IndexOfMap[T Hashable, J any](search map[T]J, value J) (T, error)

IndexOfMap returns the index of a value in a map

returns an error if the value is not found

func InstallLinuxPkg

func InstallLinuxPkg(pkg []string, man ...string)

InstallLinuxPkg attempts to install a linux package

this method will also resolve the sudo command and ask for a user password if needed

this method will not attempt to run an install, if it finds the package is already installed

func IsZeroOfUnderlyingType

func IsZeroOfUnderlyingType(x interface{}) bool

IsZeroOfUnderlyingType can be used to determine if an interface{} in null or empty

func JoinPath

func JoinPath(path ...string) (string, error)

JoinPath joins multiple file types with safety from backtracking

func MapArgs

func MapArgs(args ...[]string) map[string]string

MapArgs will convert a bash argument array ([]string) into a map (map[string]string)

When @args is left blank with no values, it will default to os.Args[1:]

-- Arg Convertions:

"--Key=value" will convert to "key:value"

"--boolKey" will convert to "boolKey:true"

"-flags" will convert to "f:true, l:true, a:true, g:true, s:true" (only if its alphanumeric [A-Za-z0-9]) if -flags is not alphanumeric (example: "-test.paniconexit0" "-test.timeout=10m0s") it will be treated as a --flag (--key=value --boolKey)

keys that match a number ("--1" or "-1") will start with a "-" ("--1=value" -> "-1:value", "-1" -> -1:true) this prevents a number key from conflicting with an index key

everything else is given a number value index starting with 0

this method will not allow --args to have their values modified after they have already been set

func MapArgsByte

func MapArgsByte(args ...[][]byte) map[string][]byte

MapArgs is just like MapArgs, but it excepts and outputs using []byte instead of string

func NewHash

func NewHash(text []byte, key []byte) ([]byte, error)

NewHash runs a key based HMAC hash using SHA256

the key is also hashed with SHA256

func ParseJson

func ParseJson(b []byte) (map[string]interface{}, error)

ParseJson converts a json string into a map of strings

func RandBytes

func RandBytes(size int, exclude ...[]byte) []byte

RandBytes generates random bytes using crypto/rand

@exclude[0] allows you can to pass an optional []byte to ensure that set of chars will not be included in the output string

@exclude[1] provides a replacement string to put in place of the unwanted chars

@exclude[2:] is currently ignored

func StringifyJSON

func StringifyJSON(data interface{}, ind ...int) ([]byte, error)

StringifyJSON converts a map or array to a JSON string

func ToArray

func ToArray(res interface{}) []interface{}

ToArray converts multiple types to an []interface{}

func ToMap

func ToMap(res interface{}) map[string]interface{}

ToMap converts multiple types to a map[string]interface{}

func ToNumber

func ToNumber[T interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr | float64 | float32
}](res interface{}) T

ToNumber converts multiple types to a number

accepts: int (and variants), string, []byte, byte, bool

func ToString

func ToString[T interface{ string | []byte }](res interface{}) T

ToString converts multiple types to a string

accepts: string, []byte, byte, int (and variants), [][]byte, []interface{}

func ToType

func ToType[T SupportedType](res interface{}) interface{}

ToType attempts to converts an interface{} from the many possible types in golang, to a specific type of your choice

if it fails to convert, it will return a nil/zero value for the appropriate type

recommended: add .(string|[]byte|int|etc) to the end of the function to get the correct type output in place of interface{}

func TrimRepeats

func TrimRepeats(b []byte, chars []byte) []byte

TrimRepeats trims repeating adjacent characters and reduces them to one character

@b: byte array to trim

@chars: list of bytes to trim repeats of

func WatchDir

func WatchDir(root string, cb *Watcher)

WatchDir watches the files in a directory and its subdirectories for changes

Types

type Hashable

type Hashable interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr | float32 | float64 | string | complex64 | complex128
}

type SupportedType added in v4.0.1

type SupportedType interface {
	string | []byte | byte | int | bool | int64 | int32 | float64 | float32 | [][]byte | []interface{} | []string | []bool | []int | []int64 | []int32 | []float64 | []float32 | map[string]interface{} | map[byte]interface{} | map[int]interface{} | map[int64]interface{} | map[int32]interface{} | map[float64]interface{} | map[float32]interface{}
}

SupportedType is an interface containing the types which are supported by the ToType method

type Watcher

type Watcher struct {
	FileChange func(path string, op string)
	DirAdd     func(path string, op string) (addWatcher bool)
	Remove     func(path string, op string) (removeWatcher bool)
	Any        func(path string, op string)
}

A watcher instance for the `WatchDir` func

Jump to

Keyboard shortcuts

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