dry

package module
v0.0.0-...-a8baca3 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2022 License: MIT Imports: 44 Imported by: 0

README

go-dry

bytes

compress

debug

crypt

binary

errors

Useful stuff to do with errors

files

http

io

net

os

path

rand

reflect

shortcuts

Useful functions to deal with go explicit result of func calling

slice

slicetricks actually.

maps

maptricks, you know.

strings

test

useful things in unit tests

time

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Deflate DeflatePool
	Gzip    GzipPool
)
View Source
var (
	AES = aesCipherPool{NewSyncPoolMap()}
)

Functions

func AsError

func AsError(r any) error

AsError returns r as error, converting it when necessary

func BigIntBytes

func BigIntBytes(v *big.Int, bitsize int) []byte

func BigIntBytesAutoChoose

func BigIntBytesAutoChoose(v *big.Int) []byte

func BytesDecodeBase64

func BytesDecodeBase64(base64Str string) string

func BytesDecodeHex

func BytesDecodeHex(hexStr string) string

func BytesDeflate

func BytesDeflate(uncompressed []byte) (compressed []byte)

func BytesEncodeBase64

func BytesEncodeBase64(str string) string

func BytesEncodeHex

func BytesEncodeHex(str string) string

func BytesFilter

func BytesFilter(f func(byte) bool, data []byte) []byte

BytesFilter filters out all bytes where the function does not return true.

func BytesGzip

func BytesGzip(uncompressed []byte) (compressed []byte)

func BytesHead

func BytesHead(data []byte, numLines int) (lines []string, rest []byte)

BytesHead returns at most numLines from data starting at the beginning. A slice of the remaining data is returned as rest. \n is used to detect line ends, a preceding \r will be stripped away. BytesHead resembles the Unix head command.

func BytesInflate

func BytesInflate(compressed []byte) (uncompressed []byte)

func BytesMD5

func BytesMD5(data string) string

func BytesMap

func BytesMap(f func(byte) byte, data []byte) []byte

BytesMap maps a function on each element of a slice of bytes.

func BytesReader

func BytesReader(data any) io.Reader

func BytesTail

func BytesTail(data []byte, numLines int) (lines []string, rest []byte)

BytesTail returns at most numLines from the end of data. A slice of the remaining data before lines is returned as rest. \n is used to detect line ends, a preceding \r will be stripped away. BytesTail resembles the Unix tail command.

func BytesUnGzip

func BytesUnGzip(compressed []byte) (uncompressed []byte)

func BytesXor

func BytesXor(a, b []byte) []byte

func ConvertFloat

func ConvertFloat(n interface{}) float64

func ConvertInt

func ConvertInt(n interface{}) int

func DecryptAES

func DecryptAES(key []byte, ciphertext []byte) []byte

DecryptAES decrypts ciphertext using AES with the given key. key should be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

func EncryptAES

func EncryptAES(key []byte, plaintext []byte) []byte

EncryptAES encrypts plaintext using AES with the given key. key should be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. plaintext must not be shorter than key.

func EndianIsBig

func EndianIsBig() bool

func EndianIsLittle

func EndianIsLittle() bool

func EndianSafeSplitUint16

func EndianSafeSplitUint16(value uint16) (leastSignificant, mostSignificant uint8)

func EnvironMap

func EnvironMap() map[string]string

EnvironMap returns the current environment variables as a map.

func FileAppendBytes

func FileAppendBytes(filename string, data []byte) error

func FileAppendPrintf

func FileAppendPrintf(filename, format string, args ...any) error

func FileAppendString

func FileAppendString(filename string, data string) error

func FileBufferedReader

func FileBufferedReader(filenameOrURL string) (io.Reader, error)

func FileCRC64

func FileCRC64(filenameOrURL string) (uint64, error)

func FileCopy

func FileCopy(source string, dest string) (err error)

FileCopy copies file source to destination dest. Based on Jaybill McCarthy's code which can be found at http://jayblog.jaybill.com/post/id/26

func FileCopyDir

func FileCopyDir(source string, dest string) (err error)

FileCopyDir recursively copies a directory tree, attempting to preserve permissions. Source directory must exist, destination directory must *not* exist. Based on Jaybill McCarthy's code which can be found at http://jayblog.jaybill.com/post/id/26

func FileExists

func FileExists(filename string) bool

func FileFind

func FileFind(searchDirs []string, filenames ...string) (filePath string, found bool)

func FileFindModified

func FileFindModified(searchDirs []string, filenames ...string) (filePath string, found bool, modified time.Time)

func FileGetBytes

func FileGetBytes(filenameOrURL string, timeout ...time.Duration) ([]byte, error)

func FileGetCSV

func FileGetCSV(filenameOrURL string, timeout ...time.Duration) ([][]string, error)

func FileGetConfig

func FileGetConfig(filenameOrURL string, timeout ...time.Duration) (map[string]string, error)

func FileGetGz

func FileGetGz(filenameOrURL string) ([]byte, error)

func FileGetInflate

func FileGetInflate(filenameOrURL string) ([]byte, error)

func FileGetJSON

func FileGetJSON(filenameOrURL string, timeout ...time.Duration) (result any, err error)

func FileGetLastLine

func FileGetLastLine(filenameOrURL string, timeout ...time.Duration) (line string, err error)

FileGetLastLine reads the last line from a file. In case of a network file, the whole file is read. In case of a local file, the last 64kb are read, so if the last line is longer than 64kb it is not returned completely. The first optional timeout is used for network files only.

func FileGetLines

func FileGetLines(filenameOrURL string, timeout ...time.Duration) (lines []string, err error)

FileGetLines returns a string slice with the text lines of filenameOrURL. The lines can be separated by \n or \r\n.

func FileGetNonEmptyLines

func FileGetNonEmptyLines(filenameOrURL string, timeout ...time.Duration) (lines []string, err error)

FileGetNonEmptyLines returns a string slice with the non empty text lines of filenameOrURL. The lines can be separated by \n or \r\n.

func FileGetString

func FileGetString(filenameOrURL string, timeout ...time.Duration) (string, error)

func FileGetXML

func FileGetXML(filenameOrURL string, timeout ...time.Duration) (result any, err error)

func FileIsDir

func FileIsDir(dirname string) bool

func FileMD5Bytes

func FileMD5Bytes(filenameOrURL string) ([]byte, error)

func FileMD5String

func FileMD5String(filenameOrURL string) (string, error)

func FilePrintf

func FilePrintf(filename, format string, args ...any) error

func FileScanf

func FileScanf(filename, format string, args ...any) error

func FileSetBytes

func FileSetBytes(filename string, data []byte) error

func FileSetCSV

func FileSetCSV(filename string, records [][]string) error

func FileSetConfig

func FileSetConfig(filename string, config map[string]string) error

func FileSetDeflate

func FileSetDeflate(filename string, data []byte) error

func FileSetGz

func FileSetGz(filename string, data []byte) error

func FileSetJSON

func FileSetJSON(filename string, data any) error

func FileSetJSONIndent

func FileSetJSONIndent(filename string, data any, indent string) error

func FileSetLines

func FileSetLines(filename string, lines []string) error

func FileSetString

func FileSetString(filename string, data string) error

func FileSetXML

func FileSetXML(filename string, data any) error

func FileSize

func FileSize(filename string) int64

FileSize returns the size of a file or zero in case of an error.

func FileTimeModified

func FileTimeModified(filename string) time.Time

FileTimeModified returns the modified time of a file, or the zero time value in case of an error.

func FileTouch

func FileTouch(filename string) error

func FileUnmarshallJSON

func FileUnmarshallJSON(filenameOrURL string, result any, timeout ...time.Duration) error

func FileUnmarshallXML

func FileUnmarshallXML(filenameOrURL string, result any, timeout ...time.Duration) error

func FirstArg

func FirstArg(args ...any) any

FirstArg returns the first passed argument, can be used to extract first result value from a function call to pass it on to functions like fmt.Printf

func FirstError

func FirstError(errs ...error) error

FirstError returns the first non nil error, or nil

func GetError

func GetError(args ...any) error

GetError returns the last argument that is of type error, panics if none of the passed args is of type error. Note that GetError(nil) will panic because nil is not of type error but interface{}

func GetenvDefault

func GetenvDefault(key, defaultValue string) string

GetenvDefault retrieves the value of the environment variable named by the key. It returns the given defaultValue if the variable is not present.

func HTTPCompressHandlerFunc

func HTTPCompressHandlerFunc(handlerFunc http.HandlerFunc) http.HandlerFunc

HTTPCompressHandlerFunc wraps a http.HandlerFunc so that the response gets gzip or deflate compressed if the Accept-Encoding header of the request allows it.

func HTTPDelete

func HTTPDelete(url string) (statusCode int, statusText string, err error)

HTTPDelete performs a HTTP DELETE request

func HTTPPostForm

func HTTPPostForm(url string, data url.Values) (statusCode int, statusText string, err error)

HTTPPostForm performs a HTTP POST request with data as application/x-www-form-urlencoded

func HTTPPostJSON

func HTTPPostJSON(url string, data any) error

HTTPPostJSON marshalles data as JSON and sends it as HTTP POST request to url. If the response status code is not 200 OK, then the status is returned as an error.

func HTTPPostXML

func HTTPPostXML(url string, data any) error

HTTPPostXML marshalles data as XML and sends it as HTTP POST request to url. If the response status code is not 200 OK, then the status is returned as an error.

func HTTPPutForm

func HTTPPutForm(url string, data url.Values) (statusCode int, statusText string, err error)

HTTPPutForm performs a HTTP PUT request with data as application/x-www-form-urlencoded

func HTTPRespondMarshalIndentJSON

func HTTPRespondMarshalIndentJSON(response any, prefix, indent string, responseWriter http.ResponseWriter, request *http.Request) (err error)

HTTPRespondMarshalIndentJSON marshals response as JSON to responseWriter, sets Content-Type to application/json and compresses the response if Content-Encoding from the request allows it. The JSON will be marshalled indented according to json.MarshalIndent

func HTTPRespondMarshalIndentXML

func HTTPRespondMarshalIndentXML(response any, rootElement string, prefix, indent string, responseWriter http.ResponseWriter, request *http.Request) (err error)

HTTPRespondMarshalIndentXML marshals response as XML to responseWriter, sets Content-Type to application/xml and compresses the response if Content-Encoding from the request allows it. The XML will be marshalled indented according to xml.MarshalIndent. If rootElement is not empty, then an additional root element with this name will be wrapped around the content.

func HTTPRespondMarshalJSON

func HTTPRespondMarshalJSON(response any, responseWriter http.ResponseWriter, request *http.Request) (err error)

HTTPRespondMarshalJSON marshals response as JSON to responseWriter, sets Content-Type to application/json and compresses the response if Content-Encoding from the request allows it.

func HTTPRespondMarshalXML

func HTTPRespondMarshalXML(response any, rootElement string, responseWriter http.ResponseWriter, request *http.Request) (err error)

HTTPRespondMarshalXML marshals response as XML to responseWriter, sets Content-Type to application/xml and compresses the response if Content-Encoding from the request allows it. If rootElement is not empty, then an additional root element with this name will be wrapped around the content.

func HTTPRespondText

func HTTPRespondText(response string, responseWriter http.ResponseWriter, request *http.Request) (err error)

HTTPRespondText sets Content-Type to text/plain and compresses the response if Content-Encoding from the request allows it.

func HTTPUnmarshalRequestBodyJSON

func HTTPUnmarshalRequestBodyJSON(request *http.Request, result any) error

HTTPUnmarshalRequestBodyJSON reads a http.Request body and unmarshals it as JSON to result.

func IsTestMode

func IsTestMode() bool

func LastError

func LastError(errs ...error) error

LastError returns the last non nil error, or nil

func ListDir

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

func ListDirDirectories

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

func ListDirFiles

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

func MapKeys

func MapKeys(in any) any

map[<K>]<V> -> []<K> // (K, V) could be any type

func NetHostname

func NetHostname() string

func NetIP

func NetIP() string

NetIP returns the primary IP address of the system or an empty string.

func Nop

func Nop(dummiesIn ...any) (dummyOut any)

Nop is a dummy function that can be called in source files where other debug functions are constantly added and removed. That way import "github.com/ungerik/go-quick" won't cause an error when no other debug function is currently used. Arbitrary objects can be passed as arguments to avoid "declared and not used" error messages when commenting code out and in. The result is a nil interface{} dummy value.

func PanicIf

func PanicIf(condition bool, i ...any)

func PanicIfErr

func PanicIfErr(args ...any)

PanicIfErr panics with a stack trace if any of the passed args is a non nil error

func PathIsWritable

func PathIsWritable(path string) bool

func PathNearestExisting

func PathNearestExisting(path string) string

func PathSplitExt

func PathSplitExt(path string) (basepath, ext string)

делить название файла на само название и расширение при этом на название не влияет путь, в котором расположен файл

func PathWithoutExt

func PathWithoutExt(filename string) string

func PlatformEndianess

func PlatformEndianess() binary.ByteOrder

func PrettyPrintAsJSON

func PrettyPrintAsJSON(input any, indent ...string) error

PrettyPrintAsJSON marshalles input as indented JSON and calles fmt.Println with the result. If indent arguments are given, they are joined into a string and used as JSON line indent. If no indet argument is given, two spaces will be used to indent JSON lines.

func RandSeedWithTime

func RandSeedWithTime()

RandSeedWithTime calls rand.Seed() with the current time.

func RandomBytes

func RandomBytes(size int) []byte

func RandomChoose

func RandomChoose(items ...any) any

deprecated except for strings. you can copy this oneline implementation

func RandomChooseString

func RandomChooseString(items ...string) string

deprecated except for strings. you can copy this oneline implementation

func RandomHEXString

func RandomHEXString(length int) string

RandomHEXString returns a random upper case hex string with length.

func RandomHexString

func RandomHexString(length int) string

RandomHexString returns a random lower case hex string with length.

func RangeDate

func RangeDate(start, end time.Time) []time.Time

func ReadBinary

func ReadBinary(r io.Reader, order binary.ByteOrder, data any) (n int, err error)

! DEPRECATED ReadBinary wraps binary.Read with a CountingReader and returns the acutal bytes read by it.

func ReadLine

func ReadLine(reader io.Reader) (line string, err error)

! DEPRECATED ReadLine reads unbuffered until a newline '\n' byte and removes an optional carriege return '\r' at the end of the line. In case of an error, the string up to the error is returned.

func RealNetIP

func RealNetIP() string

RealNetIP returns the real local IP of the system or an empty string.

func ReflectExportedStructFields

func ReflectExportedStructFields(v reflect.Value) map[string]reflect.Value

ReflectExportedStructFields returns a map from exported struct field names to values, inlining anonymous sub-structs so that their field names are available at the base level. Example:

type A struct {
	X int
}
type B Struct {
	A
	Y int
}
// Yields X and Y instead of A and Y:
ReflectExportedStructFields(reflect.ValueOf(B{}))

func ReflectIsInteger

func ReflectIsInteger(i any) bool

func ReflectIsIntgerType

func ReflectIsIntgerType(t reflect.Type) bool

func ReflectLess

func ReflectLess(a, b interface{}) bool

true if a < b

func ReflectNameIsExported

func ReflectNameIsExported(name string) bool

func ReflectSetStructFieldString

func ReflectSetStructFieldString(structPtr any, name, value string) error

ReflectSetStructFieldString sets the field with name to value.

func ReflectSetStructFieldsFromStringMap

func ReflectSetStructFieldsFromStringMap(structPtr any, m map[string]string, errOnMissingField bool) error

ReflectSetStructFieldsFromStringMap sets the fields of a struct with the field names and values taken from a map[string]string. If errOnMissingField is true, then all fields must exist.

func ReflectSort

func ReflectSort(slice, compareFunc any)

ReflectSort will sort slice according to compareFunc using reflection. slice can be a slice of any element type including interface{}. compareFunc must have two arguments that are assignable from the slice element type or pointers to such a type. The result of compareFunc must be a bool indicating if the first argument is less than the second. If the element type of slice is interface{}, then the type of the compareFunc arguments can be any type and dynamic casting from the interface value or its address will be attempted.

func ReflectStructFieldIsExported

func ReflectStructFieldIsExported(structField reflect.StructField) bool

func ReflectTypeOfError

func ReflectTypeOfError() reflect.Type

ReflectTypeOfError returns the built-in error type

func SetUnify

func SetUnify(a, b any) any

func SetsEqual

func SetsEqual(a, b []string) bool

пока только строчки, потом сделаю нормальный интерфейс

func Sha1

func Sha1(input string) []byte

func Sha1Byte

func Sha1Byte(input []byte) []byte

func Sha3256

func Sha3256(text string) []byte

func Sha3512

func Sha3512(text string) []byte

func Sha3512Hex

func Sha3512Hex(text string) string

func SliceContains

func SliceContains(slice, item any) bool

func SliceCut

func SliceCut(slice any, i, j int) any

func SliceDeleteIndex

func SliceDeleteIndex(slice any, i int) any

func SliceExpand

func SliceExpand(slice any, i, j int) any

func SliceForEach

func SliceForEach(slice any, f func(index int, i any))

SliceForEach is special function, when you just know, that some variable is slice. try to not use this func instead, for _,_ := range _ is WAY MORE preferrable. This func is only is useful for rarest situtations

func SliceIndex

func SliceIndex(slice, item any) int

индекс элемента T в []T выводит индекс найденого элемента, либо -1, если элемент не найден

func SlicePopFunc

func SlicePopFunc(slice any, f func(i any) bool) (res, popped any)

if f func returns true, than slice item will pop

func SliceRemoveFunc

func SliceRemoveFunc(slice any, f func(i any) bool) any

func SliceToInterfaceSlice

func SliceToInterfaceSlice(in any) []any

SliceToInterfaceSlice converts a slice of any type into a slice of interface{}.

func SliceUnique

func SliceUnique(in any) any

[]<T> -> map[<T>]struct{}

func StackTrace

func StackTrace(skipFrames int) string

func StackTraceLine

func StackTraceLine(skipFrames int) string

func StringAddURLParam

func StringAddURLParam(url, name, value string) string

func StringCSV

func StringCSV(records [][]string) string

func StringConvertTime

func StringConvertTime(timeString, formatIn, formatOut string) (resultTime string, err error)

func StringEndsWithNumber

func StringEndsWithNumber(s string) bool

func StringEscapeJSON

func StringEscapeJSON(jsonString string) string

func StringFilter

func StringFilter(f func(string) bool, data []string) []string

Filter out all strings where the function does not return true.

func StringFind

func StringFind(s, token string) (remainder string, found bool)

StringFind returns in found if token has been found in s, and returns the remaining string afte token in remainder. The whole string s will be returned if found is false.

func StringFindBetween

func StringFindBetween(s, start, stop string) (between, remainder string, found bool)

StringFindBetween returns the string between the first occurrences of the tokens start and stop. The remainder of the string after the stop token will be returned if found. If the tokens couldn't be found, then the whole string will be returned as remainder.

func StringFormatBigInt

func StringFormatBigInt(mem uint64) string

func StringFormatMemory

func StringFormatMemory(mem uint64) string

func StringInSlice

func StringInSlice(s string, slice []string) bool

func StringJoin

func StringJoin(values any, sep string) string

StringJoin formats every value in values according to its default formatting and joins the result with sep as separator. values must be a slice of a formatable type

func StringJoinFormat

func StringJoinFormat(format string, values any, sep string) string

StringJoinFormat formats every value in values with format and joins the result with sep as separator. values must be a slice of a formatable type

func StringListContains

func StringListContains(l []string, s string) bool

func StringListContainsCaseInsensitive

func StringListContainsCaseInsensitive(l []string, s string) bool

func StringMD5Hex

func StringMD5Hex(data string) string

StringMD5Hex returns the hex encoded MD5 hash of data

func StringMap

func StringMap(f func(string) string, data []string) []string

Map a function on each element of a slice of strings.

func StringMapGroupedNumberPostfixSortedKeys

func StringMapGroupedNumberPostfixSortedKeys(m map[string]string) []string

func StringMapGroupedNumberPostfixSortedValues

func StringMapGroupedNumberPostfixSortedValues(m map[string]string) []string

func StringMapSortedKeys

func StringMapSortedKeys(m map[string]string) []string

func StringMarshalJSON

func StringMarshalJSON(data any, indent string) string

StringMarshalJSON marshals data to an indented string.

func StringPrettifyJSON

func StringPrettifyJSON(compactJSON string) string

func StringReplaceHTMLTags

func StringReplaceHTMLTags(text, replacement string) (plainText string)

StringReplaceHTMLTags replaces HTML/XML tags from text with replacement.

func StringReplaceMulti

func StringReplaceMulti(str string, fromTo ...string) string

func StringSHA1Base64

func StringSHA1Base64(data string) string

StringSHA1Base64 returns the base64 encoded SHA1 hash of data

func StringSplitNumberPostfix

func StringSplitNumberPostfix(s string) (base, number string)

func StringSplitOnce

func StringSplitOnce(s, sep string) (pre, post string)

func StringSplitOnceChar

func StringSplitOnceChar(s string, sep byte) (pre, post string)

func StringSplitOnceRune

func StringSplitOnceRune(s string, sep rune) (pre, post string)

func StringStripHTMLTags

func StringStripHTMLTags(text string) (plainText string)

StringStripHTMLTags strips HTML/XML tags from text.

func StringToBool

func StringToBool(s string) bool

func StringToFloat

func StringToFloat(s string) float64

func StringToInt

func StringToInt(s string) int

func StringToLowerCamelCase

func StringToLowerCamelCase(str string) string

func StringToUpperCamelCase

func StringToUpperCamelCase(str string) string

func StringsCRLF

func StringsCRLF(in string) string

func StringsCommonPrefix

func StringsCommonPrefix(a, b string) string

func TestGetCurrentPackagePath

func TestGetCurrentPackagePath() string

func WaitForStdin

func WaitForStdin(v ...any) byte

! DEPRECATED WaitForStdin blocks until input is available from os.Stdin. The first byte from os.Stdin is returned as result. If there are println arguments, then fmt.Println will be called with those before reading from os.Stdin.

func WriteFull

func WriteFull(data []byte, writer io.Writer) (n int, err error)

WriteFull calls writer.Write until all of data is written, or an is error returned.

Types

type CancelableReader

type CancelableReader = dry_ioutil.CancelableReader

CancelableReader позволяет читать данные с контекстом

func NewCancelableReader

func NewCancelableReader(ctx context.Context, r io.Reader) *CancelableReader

type CountingReadWriter

type CountingReadWriter struct {
	ReadWriter   io.ReadWriter
	BytesRead    int
	BytesWritten int
}

TODO: принцип интересный, но не входит в рамки io

func (*CountingReadWriter) Read

func (rw *CountingReadWriter) Read(p []byte) (n int, err error)

func (*CountingReadWriter) Write

func (rw *CountingReadWriter) Write(p []byte) (n int, err error)

type DebugMutex

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

DebugMutex wraps a sync.Mutex and adds debug output

func (*DebugMutex) Lock

func (d *DebugMutex) Lock()

func (*DebugMutex) Unlock

func (d *DebugMutex) Unlock()

type DebugRWMutex

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

DebugRWMutex wraps a sync.RWMutex and adds debug output

func (*DebugRWMutex) Lock

func (d *DebugRWMutex) Lock()

func (*DebugRWMutex) RLock

func (d *DebugRWMutex) RLock()

func (*DebugRWMutex) RLocker

func (d *DebugRWMutex) RLocker() sync.Locker

func (*DebugRWMutex) RUnlock

func (d *DebugRWMutex) RUnlock()

func (*DebugRWMutex) Unlock

func (d *DebugRWMutex) Unlock()

type DeflatePool

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

DeflatePool manages a pool of flate.Writer flate.NewWriter allocates a lot of memory, so if flate.Writer are needed frequently, it's more efficient to use a pool of them. The pool uses sync.Pool internally.

func (*DeflatePool) GetWriter

func (pool *DeflatePool) GetWriter(dst io.Writer) (writer *flate.Writer)

GetWriter returns flate.Writer from the pool, or creates a new one with flate.BestCompression if the pool is empty.

func (*DeflatePool) ReturnWriter

func (pool *DeflatePool) ReturnWriter(writer *flate.Writer)

ReturnWriter returns a flate.Writer to the pool that can late be reused via GetWriter. Don't close the writer, Flush will be called before returning it to the pool.

type ErrorList

type ErrorList []error

ErrorList holds a slice of errors.

Usage example:

func maybeError() (int, error) {
	return
}

func main() {
	e := NewErrorList(maybeError())
	e.Collect(maybeError())
	e.Collect(maybeError())

	if e.Err() != nil {
		fmt.Println("Some calls of maybeError() returned errors:", e)
	} else {
		fmt.Println("No call of maybeError() returned an error")
	}
}

func AsErrorList

func AsErrorList(err error) ErrorList

AsErrorList checks if err is already an ErrorList and returns it if this is the case. Else an ErrorList with err as element is created. Useful if a function potentially returns an ErrorList as error and you want to avoid creating nested ErrorLists.

func NewErrorList

func NewErrorList(args ...any) (list ErrorList)

NewErrorList returns an ErrorList where Collect has been called for args. The returned list will be nil if there was no non nil error in args. Note that alle methods of ErrorList can be called with a nil ErrorList.

func (*ErrorList) Collect

func (list *ErrorList) Collect(args ...any)

Collect adds any non nil errors in args to the list.

func (ErrorList) Err

func (list ErrorList) Err() error

Err returns the list if it is not empty, or nil if it is empty. Can be called for a nil ErrorList.

func (ErrorList) Error

func (list ErrorList) Error() string

Error calls fmt.Println for of every error in the list and returns the concernated text. Can be called for a nil ErrorList.

func (ErrorList) First

func (list ErrorList) First() error

First returns the first error in the list or nil. Can be called for a nil ErrorList.

func (ErrorList) Last

func (list ErrorList) Last() error

Last returns the last error in the list or nil. Can be called for a nil ErrorList.

type FileCopyError

type FileCopyError struct {
	What string
}

FileCopyError is a struct for returning file copy error messages

func (*FileCopyError) Error

func (e *FileCopyError) Error() string

type GzipPool

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

GzipPool manages a pool of gzip.Writer. The pool uses sync.Pool internally.

func (*GzipPool) GetWriter

func (pool *GzipPool) GetWriter(dst io.Writer) (writer *gzip.Writer)

GetWriter returns gzip.Writer from the pool, or creates a new one with gzip.BestCompression if the pool is empty.

func (*GzipPool) ReturnWriter

func (pool *GzipPool) ReturnWriter(writer *gzip.Writer)

ReturnWriter returns a gzip.Writer to the pool that can late be reused via GetWriter. Don't close the writer, Flush will be called before returning it to the pool.

type HTTPCompressHandler

type HTTPCompressHandler struct {
	http.Handler
}

HTTPCompressHandler wraps a http.Handler so that the response gets gzip or deflate compressed if the Accept-Encoding header of the request allows it.

func NewHTTPCompressHandler

func NewHTTPCompressHandler(handler http.Handler) *HTTPCompressHandler

func NewHTTPCompressHandlerFromFunc

func NewHTTPCompressHandlerFromFunc(handler http.HandlerFunc) *HTTPCompressHandler

func (*HTTPCompressHandler) ServeHTTP

func (h *HTTPCompressHandler) ServeHTTP(response http.ResponseWriter, request *http.Request)

type ReadCounter

type ReadCounter = dry_ioutil.ReadCounter

func CountingReader

func CountingReader(r io.Reader) ReadCounter

type ReaderFunc

type ReaderFunc = dry_ioutil.ReaderFunc

ReaderFunc implements io.Reader as function type with a Read method.

type StringBuilder

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

func (*StringBuilder) Bool

func (s *StringBuilder) Bool(value bool) *StringBuilder

func (*StringBuilder) Byte

func (s *StringBuilder) Byte(value byte) *StringBuilder

func (*StringBuilder) Bytes

func (s *StringBuilder) Bytes() []byte

func (*StringBuilder) Float

func (s *StringBuilder) Float(value float64) *StringBuilder

func (*StringBuilder) Int

func (s *StringBuilder) Int(value int) *StringBuilder

func (*StringBuilder) Printf

func (s *StringBuilder) Printf(format string, args ...any) *StringBuilder

func (*StringBuilder) String

func (s *StringBuilder) String() string

func (*StringBuilder) Uint

func (s *StringBuilder) Uint(value uint) *StringBuilder

func (*StringBuilder) Write

func (s *StringBuilder) Write(strings ...string) *StringBuilder

func (*StringBuilder) WriteBytes

func (s *StringBuilder) WriteBytes(bytes []byte) *StringBuilder

func (*StringBuilder) WriteTo

func (s *StringBuilder) WriteTo(writer io.Writer) (n int64, err error)

type StringGroupedNumberPostfixSorter

type StringGroupedNumberPostfixSorter []string

func (StringGroupedNumberPostfixSorter) Len

Len is the number of elements in the collection.

func (StringGroupedNumberPostfixSorter) Less

Less reports whether the element with index i should sort before the element with index j.

func (StringGroupedNumberPostfixSorter) Swap

Swap swaps the elements with indexes i and j.

type StringSet

type StringSet map[string]null

StringSet wraps map[string]struct{} with some useful methods.

func (StringSet) Clone

func (set StringSet) Clone() StringSet

func (StringSet) Delete

func (set StringSet) Delete(s string)

func (StringSet) Exclude

func (set StringSet) Exclude(other StringSet)

func (StringSet) Has

func (set StringSet) Has(s string) bool

func (StringSet) Join

func (set StringSet) Join(other StringSet)

func (StringSet) ReverseSorted

func (set StringSet) ReverseSorted() []string

func (StringSet) Set

func (set StringSet) Set(s string)

func (StringSet) Sorted

func (set StringSet) Sorted() []string

type SyncBool

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

func NewSyncBool

func NewSyncBool(value bool) *SyncBool

func (*SyncBool) Get

func (s *SyncBool) Get() bool

func (*SyncBool) Invert

func (s *SyncBool) Invert() bool

func (*SyncBool) Set

func (s *SyncBool) Set(value bool)

func (*SyncBool) Swap

func (s *SyncBool) Swap(value bool) bool

type SyncFloat

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

func NewSyncFloat

func NewSyncFloat(value float64) *SyncFloat

func (*SyncFloat) Add

func (s *SyncFloat) Add(value float64) float64

func (*SyncFloat) Get

func (s *SyncFloat) Get() float64

func (*SyncFloat) Mul

func (s *SyncFloat) Mul(value float64) float64

func (*SyncFloat) Set

func (s *SyncFloat) Set(value float64)

func (*SyncFloat) Swap

func (s *SyncFloat) Swap(value float64) float64

type SyncInt

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

func NewSyncInt

func NewSyncInt(value int) *SyncInt

func (*SyncInt) Add

func (s *SyncInt) Add(value int) int

func (*SyncInt) Get

func (s *SyncInt) Get() int

func (*SyncInt) Mul

func (s *SyncInt) Mul(value int) int

func (*SyncInt) Set

func (s *SyncInt) Set(value int)

func (*SyncInt) Swap

func (s *SyncInt) Swap(value int) int

type SyncMap

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

func NewSyncMap

func NewSyncMap() *SyncMap

func (*SyncMap) Add

func (s *SyncMap) Add(key string, value any)

func (*SyncMap) AddBool

func (s *SyncMap) AddBool(key string, value bool)

func (*SyncMap) AddFloat

func (s *SyncMap) AddFloat(key string, value float64)

func (*SyncMap) AddInt

func (s *SyncMap) AddInt(key string, value int)

func (*SyncMap) AddString

func (s *SyncMap) AddString(key string, value string)

func (*SyncMap) Bool

func (s *SyncMap) Bool(key string) *SyncBool

func (*SyncMap) Delete

func (s *SyncMap) Delete(key string)

func (*SyncMap) Float

func (s *SyncMap) Float(key string) *SyncFloat

func (*SyncMap) Get

func (s *SyncMap) Get(key string) any

func (*SyncMap) Has

func (s *SyncMap) Has(key string) bool

func (*SyncMap) Int

func (s *SyncMap) Int(key string) *SyncInt

func (*SyncMap) String

func (s *SyncMap) String(key string) *SyncString

type SyncPoolMap

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

func NewSyncPoolMap

func NewSyncPoolMap() *SyncPoolMap

func (*SyncPoolMap) Add

func (s *SyncPoolMap) Add(key string, value *sync.Pool)

func (*SyncPoolMap) Delete

func (s *SyncPoolMap) Delete(key string)

func (*SyncPoolMap) Get

func (s *SyncPoolMap) Get(key string) *sync.Pool

func (*SyncPoolMap) GetOrAddNew

func (s *SyncPoolMap) GetOrAddNew(key string, newFunc func() any) *sync.Pool

func (*SyncPoolMap) Has

func (s *SyncPoolMap) Has(key string) bool

type SyncString

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

func NewSyncString

func NewSyncString(value string) *SyncString

func (*SyncString) Append

func (s *SyncString) Append(value string) string

func (*SyncString) Get

func (s *SyncString) Get() string

func (*SyncString) Set

func (s *SyncString) Set(value string)

func (*SyncString) Swap

func (s *SyncString) Swap(value string) string

type SyncStringMap

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

func NewSyncStringMap

func NewSyncStringMap() *SyncStringMap

func (*SyncStringMap) Add

func (s *SyncStringMap) Add(key string, value string)

func (*SyncStringMap) Delete

func (s *SyncStringMap) Delete(key string)

func (*SyncStringMap) Get

func (s *SyncStringMap) Get(key string) string

func (*SyncStringMap) Has

func (s *SyncStringMap) Has(key string) bool

type WriteCounter

type WriteCounter = dry_ioutil.WriteCounter

func CountingWriter

func CountingWriter(w io.Writer) WriteCounter

type WriterFunc

type WriterFunc = dry_ioutil.WriterFunc

WriterFunc implements io.Writer as function type with a Write method.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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