util

package
v2.0.0-...-83f77b2 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2022 License: AGPL-3.0 Imports: 33 Imported by: 0

Documentation

Overview

Package util provides some common utility methods

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ByteCountIEC

func ByteCountIEC(b int64) string

ByteCountIEC returns humanized size in IEC (binary) format

func ByteCountSI

func ByteCountSI(b int64) string

ByteCountSI returns humanized size in SI (decimal) format

func CheckTCP4Port

func CheckTCP4Port(port int)

CheckTCP4Port quits the app if bind on the given IPv4 port fails. This is a ugly hack to avoid to bind on an already used port. It is required on Windows only. Upstream does not consider this behaviour a bug: https://github.com/golang/go/issues/45150

func CleanDirInput

func CleanDirInput(dirInput string) string

CleanDirInput sanitizes user input for directories. On Windows it removes any trailing `"`. We try to help windows users that set an invalid path such as "C:\ProgramData\SFTPGO\". This will only help if the invalid path is the last argument, for example in this command: sftpgo.exe serve -c "C:\ProgramData\SFTPGO\" -l "sftpgo.log" the -l flag will be ignored and the -c flag will get the value `C:\ProgramData\SFTPGO" -l sftpgo.log` since the backslash after SFTPGO escape the double quote. This is definitely a bad user input

func CleanPath

func CleanPath(p string) string

CleanPath returns a clean POSIX (/) absolute path to work with

func CleanPathWithBase

func CleanPathWithBase(base, p string) string

CleanPathWithBase returns a clean POSIX (/) absolute path to work with. The specified base will be used if the provided path is not absolute

func Contains

func Contains[T comparable](elems []T, v T) bool

Contains reports whether v is present in elems.

func EncodeTLSCertToPem

func EncodeTLSCertToPem(tlsCert *x509.Certificate) (string, error)

EncodeTLSCertToPem returns the specified certificate PEM encoded. This can be verified using openssl x509 -in cert.crt -text -noout

func FindSharedDataPath

func FindSharedDataPath(name, searchDir string) string

FindSharedDataPath searches for the specified directory name in searchDir and in system-wide shared data directories. If name is an absolute path it is returned unmodified.

func GenerateECDSAKeys

func GenerateECDSAKeys(file string) error

GenerateECDSAKeys generate ecdsa private and public keys and write the private key to specified file and the public key to the specified file adding the .pub suffix

func GenerateEd25519Keys

func GenerateEd25519Keys(file string) error

GenerateEd25519Keys generate ed25519 private and public keys and write the private key to specified file and the public key to the specified file adding the .pub suffix

func GenerateRSAKeys

func GenerateRSAKeys(file string) error

GenerateRSAKeys generate rsa private and public keys and write the private key to specified file and the public key to the specified file adding the .pub suffix

func GenerateRandomBytes

func GenerateRandomBytes(length int) []byte

GenerateRandomBytes generates the secret to use for JWT auth

func GenerateUniqueID

func GenerateUniqueID() string

GenerateUniqueID retuens an unique ID

func GetAbsolutePath

func GetAbsolutePath(name string) (string, error)

GetAbsolutePath returns an absolute path using the current dir as base if name defines a relative path

func GetDirsForVirtualPath

func GetDirsForVirtualPath(virtualPath string) []string

GetDirsForVirtualPath returns all the directory for the given path in reverse order for example if the path is: /1/2/3/4 it returns: [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]

func GetDurationAsString

func GetDurationAsString(d time.Duration) string

GetDurationAsString returns a string representation for a time.Duration

func GetHTTPLocalAddress

func GetHTTPLocalAddress(r *http.Request) string

GetHTTPLocalAddress returns the local address for an http.Request or empty if it cannot be determined

func GetIPFromRemoteAddress

func GetIPFromRemoteAddress(remoteAddress string) string

GetIPFromRemoteAddress returns the IP from the remote address. If the given remote address cannot be parsed it will be returned unchanged

func GetIntFromPointer

func GetIntFromPointer(val *int64) int64

GetIntFromPointer returns the int value or zero

func GetRealIP

func GetRealIP(r *http.Request, header string, depth int) string

GetRealIP returns the ip address as result of parsing the specified header and using the specified depth

func GetRedactedURL

func GetRedactedURL(rawurl string) string

GetRedactedURL returns the url redacting the password if any

func GetSSHPublicKeyAsString

func GetSSHPublicKeyAsString(pubKey []byte) (string, error)

GetSSHPublicKeyAsString returns an SSH public key serialized as string

func GetStringFromPointer

func GetStringFromPointer(val *string) string

GetStringFromPointer returns the string value or empty if nil

func GetTLSCiphersFromNames

func GetTLSCiphersFromNames(cipherNames []string) []uint16

GetTLSCiphersFromNames returns the TLS ciphers from the specified names

func GetTLSVersion

func GetTLSVersion(val int) uint16

GetTLSVersion returns the TLS version for integer: - 12 means TLS 1.2 - 13 means TLS 1.3 default is TLS 1.2

func GetTimeAsMsSinceEpoch

func GetTimeAsMsSinceEpoch(t time.Time) int64

GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct

func GetTimeFromMsecSinceEpoch

func GetTimeFromMsecSinceEpoch(msec int64) time.Time

GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision

func GetTimeFromPointer

func GetTimeFromPointer(val *time.Time) time.Time

GetTimeFromPointer returns the time value or now

func HTTPListenAndServe

func HTTPListenAndServe(srv *http.Server, address string, port int, isTLS bool, logSender string) error

HTTPListenAndServe is a wrapper for ListenAndServe that support both tcp and Unix-domain sockets

func IsByteArrayEmpty

func IsByteArrayEmpty(b []byte) bool

IsByteArrayEmpty return true if the byte array is empty or a new line

func IsEmailValid

func IsEmailValid(email string) bool

IsEmailValid returns true if the specified email address is valid

func IsFileInputValid

func IsFileInputValid(fileInput string) bool

IsFileInputValid returns true this is a valid file name. This method must be used before joining a file name, generally provided as user input, with a directory

func IsStringPrefixInSlice

func IsStringPrefixInSlice(obj string, list []string) bool

IsStringPrefixInSlice searches a string prefix in a slice and returns true if a matching prefix is found

func LoadTemplate

func LoadTemplate(base *template.Template, paths ...string) *template.Template

LoadTemplate parses the given template paths. It behaves like template.Must but it writes a log before exiting. You can optionally provide a base template (e.g. to define some custom functions)

func NilIfEmpty

func NilIfEmpty(s string) *string

NilIfEmpty returns nil if the input string is empty

func PanicOnError

func PanicOnError(err error)

PanicOnError calls panic if err is not nil

func ParseAllowedIPAndRanges

func ParseAllowedIPAndRanges(allowed []string) ([]func(net.IP) bool, error)

ParseAllowedIPAndRanges returns a list of functions that allow to find if an IP is equal or is contained within the allowed list

func ParseBytes

func ParseBytes(s string) (int64, error)

ParseBytes parses a string representation of bytes into the number of bytes it represents.

ParseBytes("42 MB") -> 42000000, nil ParseBytes("42 mib") -> 44040192, nil

copied from here:

https://github.com/dustin/go-humanize/blob/master/bytes.go

with minor modifications

func PrependFileInfo

func PrependFileInfo(files []os.FileInfo, info os.FileInfo) []os.FileInfo

PrependFileInfo prepends a file info to a slice in an efficient way. We, optimistically, assume that the slice has enough capacity

func Remove

func Remove(elems []string, val string) []string

Remove removes an element from a string slice and returns the modified slice

func RemoveDuplicates

func RemoveDuplicates(obj []string, trim bool) []string

RemoveDuplicates returns a new slice removing any duplicate element from the initial one

Types

type Conn

type Conn struct {
	net.Conn
	ReadTimeout              time.Duration
	WriteTimeout             time.Duration
	ReadThreshold            int32
	WriteThreshold           int32
	BytesReadFromDeadline    atomic.Int32
	BytesWrittenFromDeadline atomic.Int32
}

Conn wraps a net.Conn, and sets a deadline for every read and write operation.

func (*Conn) Read

func (c *Conn) Read(b []byte) (n int, err error)

func (*Conn) Write

func (c *Conn) Write(b []byte) (n int, err error)

type GenericError

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

GenericError raised for not well categorized error

func NewGenericError

func NewGenericError(error string) *GenericError

NewGenericError returns a generic error

func (*GenericError) Error

func (e *GenericError) Error() string

type MethodDisabledError

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

MethodDisabledError raised if a method is disabled in config file. For example, if user management is disabled, this error is raised every time a user operation is done using the REST API

func NewMethodDisabledError

func NewMethodDisabledError(error string) *MethodDisabledError

NewMethodDisabledError returns a method disabled error

func (*MethodDisabledError) Error

func (e *MethodDisabledError) Error() string

Method disabled error details

type RecordNotFoundError

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

RecordNotFoundError raised if a requested object is not found

func NewRecordNotFoundError

func NewRecordNotFoundError(error string) *RecordNotFoundError

NewRecordNotFoundError returns a not found error

func (*RecordNotFoundError) Error

func (e *RecordNotFoundError) Error() string

type ValidationError

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

ValidationError raised if input data is not valid

func NewValidationError

func NewValidationError(error string) *ValidationError

NewValidationError returns a validation errors

func (*ValidationError) Error

func (e *ValidationError) Error() string

Validation error details

func (*ValidationError) GetErrorString

func (e *ValidationError) GetErrorString() string

GetErrorString returns the unmodified error string

Jump to

Keyboard shortcuts

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