utils

package
v0.0.0-...-f0a7105 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2024 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnmarshalJSON = errors.New("unmarshalling JSON failed")
	ErrTooLargeJSON  = errors.New("too large JSON")
)

Errors for UnmarshalJSON and UnmarshalJSONWithLimit functions

Functions

func BasicAuth

func BasicAuth(user, pass string) string

BasicAuth encodes the Authorization header value for basic auth

func BearerAuth

func BearerAuth(token string) string

BearerAuth encodes the Authorization header value for a bearer/token auth

func Contains

func Contains[T comparable](haystack []T, needle T) bool

Contains returns true if needle is contained in haystack

func ContainsAll

func ContainsAll[T comparable](haystack []T, needles []T) bool

ContainsAll returns true if all needles are contained in haystack

func ContainsIP

func ContainsIP(haystack []netip.Prefix, needle netip.Addr) bool

ContainsIP returns true if any one of the of prefixes contains the ip.

func DetectContentType

func DetectContentType(b []byte, filename string) (mimeType string, ext string)

DetectContentType probes the byte array b and returns mime type and file extension. The filename is only used to override certain special cases.

func FileExists

func FileExists(filename string) bool

FileExists checks if a file exists, and returns true if it does

func FormatSize

func FormatSize(b int64) string

FormatSize formats the size in a way that it can be parsed by ParseSize. It does not include decimal places. Uneven sizes are rounded down.

func FormatSizeHuman

func FormatSizeHuman(b int64) string

FormatSizeHuman formats bytes into a human-readable notation, e.g. 2.1 MB

func Int

func Int(v int) *int

Int turns an int into a pointer of an int

func LastString

func LastString(s []string, def string) string

LastString returns the last string in a slice, or def if s is empty

func Max

func Max[T int | int64 | rate.Limit](a, b T) T

Max returns the maximum value of the two given values

func MaybeMarshalJSON

func MaybeMarshalJSON(v any) string

MaybeMarshalJSON returns a JSON string of the given object, or "<cannot serialize>" if serialization failed. This is useful for logging purposes where a failure doesn't matter that much.

func MinMax

func MinMax[T int | int64](value, min, max T) T

MinMax returns value if it is between min and max, or either min or max if it is out of range

func ParsePriority

func ParsePriority(priority string) (int, error)

ParsePriority parses a priority string into its equivalent integer value

func ParseSize

func ParseSize(s string) (int64, error)

ParseSize parses a size string like 2K or 2M into bytes. If no unit is found, e.g. 123, bytes is assumed.

func PriorityString

func PriorityString(priority int) (string, error)

PriorityString converts a priority number to a string

func QuoteCommand

func QuoteCommand(command []string) string

QuoteCommand combines a command array to a string, quoting arguments that need quoting. This function is naive, and sometimes wrong. It is only meant for lo pretty-printing a command.

Warning: Never use this function with the intent to run the resulting command.

Example:

[]string{"ls", "-al", "Document Folder"} -> ls -al "Document Folder"

func RandomLowerStringPrefix

func RandomLowerStringPrefix(prefix string, length int) string

RandomLowerStringPrefix returns a random lowercase-only string with a given length, with a prefix

func RandomString

func RandomString(length int) string

RandomString returns a random string with a given length

func RandomStringPrefix

func RandomStringPrefix(prefix string, length int) string

RandomStringPrefix returns a random string with a given length, with a prefix

func ReadPassword

func ReadPassword(in io.Reader) ([]byte, error)

ReadPassword will read a password from STDIN. If the terminal supports it, it will not print the input characters to the screen. If not, it'll just read using normal readline semantics (useful for testing).

func Retry

func Retry[T any](f func() (*T, error), after ...time.Duration) (t *T, err error)

Retry executes function f until if succeeds, and then returns t. If f fails, it sleeps and tries again. The sleep durations are passed as the after params.

func ShortTopicURL

func ShortTopicURL(s string) string

ShortTopicURL shortens the topic URL to be human-friendly, removing the http:// or https://

func SplitKV

func SplitKV(s string, sep string) (key string, value string)

SplitKV splits a string into a key/value pair using a separator, and trimming space. If the separator is not found, key is empty.

func SplitNoEmpty

func SplitNoEmpty(s string, sep string) []string

SplitNoEmpty splits a string using strings.Split, but filters out empty strings

func String

func String(v string) *string

String turns a string into a pointer of a string

func Time

func Time(v time.Time) *time.Time

Time turns a time.Time into a pointer

func UnmarshalJSON

func UnmarshalJSON[T any](body io.ReadCloser) (*T, error)

UnmarshalJSON reads the given io.ReadCloser into a struct

func UnmarshalJSONWithLimit

func UnmarshalJSONWithLimit[T any](r io.ReadCloser, limit int, allowEmpty bool) (*T, error)

UnmarshalJSONWithLimit reads the given io.ReadCloser into a struct, but only until limit is reached

func ValidRandomString

func ValidRandomString(s string, length int) bool

ValidRandomString returns true if the given string matches the format created by RandomString

Types

type PeekedReadCloser

type PeekedReadCloser struct {
	PeekedBytes  []byte
	LimitReached bool
	// contains filtered or unexported fields
}

PeekedReadCloser is a ReadCloser that allows peeking into a stream and buffering it in memory. It can be instantiated using the Peek function. After a stream has been peeked, it can still be fully read by reading the PeekedReadCloser. It first drained from the memory buffer, and then from the remaining underlying reader.

func Peek

func Peek(underlying io.ReadCloser, limit int) (*PeekedReadCloser, error)

Peek reads the underlying ReadCloser into memory up until the limit and returns a PeekedReadCloser. It does not return an error if limit is reached. Instead, LimitReached will be set to true.

func (*PeekedReadCloser) Close

func (r *PeekedReadCloser) Close() error

Close closes the underlying stream

func (*PeekedReadCloser) Read

func (r *PeekedReadCloser) Read(p []byte) (n int, err error)

Read reads from the peeked bytes and then from the underlying stream

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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