Documentation
¶
Overview ¶
Package util provides some common utility methods
Index ¶
- Constants
- Variables
- func ByteCountIEC(b int64) string
- func ByteCountSI(b int64) string
- func BytesToString(b []byte) string
- func CheckTCP4Port(port int)
- func CleanDirInput(dirInput string) string
- func CleanPath(p string) string
- func CleanPathWithBase(base, p string) string
- func EncodeTLSCertToPem(tlsCert *x509.Certificate) (string, error)
- func FindSharedDataPath(name, searchDir string) string
- func GenerateECDSAKeys(file string) error
- func GenerateEd25519Keys(file string) error
- func GenerateOpaqueString() string
- func GenerateRSAKeys(file string) error
- func GenerateRandomBytes(length int) []byte
- func GenerateUniqueID() string
- func GetACMECertificateKeyPair(domain string) (string, string)
- func GetALPNProtocols(protocols []string) []string
- func GetAbsolutePath(name string) (string, error)
- func GetDirsForVirtualPath(virtualPath string) []string
- func GetDurationAsString(d time.Duration) string
- func GetHTTPLocalAddress(r *http.Request) string
- func GetIPFromNetAddr(upstream net.Addr) (net.IP, error)
- func GetIPFromRemoteAddress(remoteAddress string) string
- func GetIntFromPointer(val *int64) int64
- func GetLastIPForPrefix(p netip.Prefix) netip.Addr
- func GetRealIP(r *http.Request, header string, depth int) string
- func GetRedactedURL(rawurl string) string
- func GetSSHPublicKeyAsString(pubKey []byte) (string, error)
- func GetStringFromPointer(val *string) string
- func GetTLSCiphersFromNames(cipherNames []string) []uint16
- func GetTLSVersion(val int) uint16
- func GetTimeAsMsSinceEpoch(t time.Time) int64
- func GetTimeFromMsecSinceEpoch(msec int64) time.Time
- func GetTimeFromPointer(val *time.Time) time.Time
- func HTTPListenAndServe(srv *http.Server, address string, port int, isTLS bool, ...) error
- func IsByteArrayEmpty(b []byte) bool
- func IsDirOverlapped(dir1, dir2 string, fullCheck bool, separator string) bool
- func IsEmailValid(email string) bool
- func IsFileInputValid(fileInput string) bool
- func IsNameValid(name string) bool
- func IsStringPrefixInSlice(obj string, list []string) bool
- func JSONEscape(val string) string
- func LoadTemplate(base *template.Template, paths ...string) *template.Template
- func NilIfEmpty(s string) *string
- func PanicOnError(err error)
- func ParseAllowedIPAndRanges(allowed []string) ([]func(net.IP) bool, error)
- func ParseBytes(s string) (int64, error)
- func ReadConfigFromFile(name, configDir string) (string, error)
- func RemoveDuplicates(obj []string, trim bool) []string
- func SanitizeCSVRow(row []string) []string
- func SanitizeDomain(domain string) string
- func SetUmask(val string)
- func SlicesEqual(s1, s2 []string) bool
- func StringToBytes(s string) []byte
- func VerifyFileChecksum(filePath string, h hash.Hash, expectedHex string, maxSize int64) error
- type GenericError
- type I18nError
- type I18nErrorOption
- type MethodDisabledError
- type RecordNotFoundError
- type ValidationError
Constants ¶
const ( I18nSetupTitle = "title.setup" I18nLoginTitle = "title.login" I18nFilesTitle = "title.files" I18nProfileTitle = "title.profile" I18nUsersTitle = "title.users" I18nGroupsTitle = "title.groups" I18nFoldersTitle = "title.folders" I18nChangePwdTitle = "title.change_password" I18n2FATitle = "title.two_factor_auth" I18nEditFileTitle = "title.edit_file" I18nViewFileTitle = "title.view_file" I18nForgotPwdTitle = "title.recovery_password" I18nResetPwdTitle = "title.reset_password" I18nInvalidAuthReqTitle = "title.invalid_auth_request" I18nError403Title = "title.error403" I18nError400Title = "title.error400" I18nError404Title = "title.error404" I18nError416Title = "title.error416" I18nError429Title = "title.error429" I18nError500Title = "title.error500" I18nErrorPDFTitle = "title.errorPDF" I18nErrorEditorTitle = "title.error_editor" I18nAddUserTitle = "title.add_user" I18nUpdateUserTitle = "title.update_user" I18nAddAdminTitle = "title.add_admin" I18nUpdateAdminTitle = "title.update_admin" I18nTemplateUserTitle = "title.template_user" I18nMaintenanceTitle = "title.maintenance" I18nConfigsTitle = "title.configs" I18nOAuth2Title = "title.oauth2_success" I18nOAuth2ErrorTitle = "title.oauth2_error" I18nSessionsTitle = "title.connections" I18nRolesTitle = "title.roles" I18nAdminsTitle = "title.admins" I18nIPListsTitle = "title.ip_lists" I18nAddIPListTitle = "title.add_ip_list" I18nUpdateIPListTitle = "title.update_ip_list" I18nDefenderTitle = "title.defender" I18nEventsTitle = "title.logs" I18nActionsTitle = "title.event_actions" I18nRulesTitle = "title.event_rules" I18nAddActionTitle = "title.add_action" I18nUpdateActionTitle = "title.update_action" I18nAddRuleTitle = "title.add_rule" I18nUpdateRuleTitle = "title.update_rule" I18nStatusTitle = "status.desc" I18nErrorSetupInstallCode = "setup.install_code_mismatch" I18nInvalidAuth = "general.invalid_auth_request" I18nError429Message = "general.error429" I18nError400Message = "general.error400" I18nError403Message = "general.error403" I18nError404Message = "general.error404" I18nError416Message = "general.error416" I18nError500Message = "general.error500" I18nErrorPDFMessage = "general.errorPDF" I18nErrorInvalidToken = "general.invalid_token" I18nErrorInvalidForm = "general.invalid_form" I18nErrorInvalidCredentials = "general.invalid_credentials" I18nErrorInvalidCSRF = "general.invalid_csrf" I18nErrorFsGeneric = "fs.err_generic" I18nErrorDirListGeneric = "fs.dir_list.err_generic" I18nErrorDirList403 = "fs.dir_list.err_403" I18nErrorDirList429 = "fs.dir_list.err_429" I18nErrorDirListUser = "fs.dir_list.err_user" I18nErrorFsValidation = "fs.err_validation" I18nErrorSecretEntropy = "fs.err_secret_entropy" I18nErrorChangePwdRequiredFields = "change_pwd.required_fields" I18nErrorChangePwdNoMatch = "change_pwd.no_match" I18nErrorChangePwdGeneric = "change_pwd.generic" I18nErrorChangePwdNoDifferent = "change_pwd.no_different" I18nErrorChangePwdCurrentNoMatch = "change_pwd.current_no_match" I18nErrorChangePwdRequired = "change_pwd.required" I18nErrorUsernameRequired = "general.username_required" I18nErrorPasswordRequired = "general.password_required" I18nErrorPermissionsRequired = "general.permissions_required" I18nErrorGetUser = "general.err_user" I18nErrorPwdResetForbidded = "login.reset_pwd_forbidden" I18nErrorPwdResetNoEmail = "login.reset_pwd_no_email" I18nErrorPwdResetSendEmail = "login.reset_pwd_send_email_err" I18nErrorPwdResetGeneric = "login.reset_pwd_err_generic" I18nErrorProtocolForbidden = "general.err_protocol_forbidden" I18nErrorPwdLoginForbidden = "general.pwd_login_forbidden" I18nErrorIPForbidden = "general.ip_forbidden" I18nErrorConnectionForbidden = "general.connection_forbidden" I18nErrorReservedUsername = "user.username_reserved" I18nErrorInvalidEmail = "general.email_invalid" I18nErrorInvalidInput = "general.invalid_input" I18nErrorInvalidUser = "user.username_invalid" I18nErrorInvalidName = "general.name_invalid" I18nErrorHomeRequired = "user.home_required" I18nErrorHomeInvalid = "user.home_invalid" I18nErrorPubKeyInvalid = "user.pub_key_invalid" I18nErrorPrivKeyInvalid = "user.priv_key_invalid" I18nErrorKeySizeInvalid = "user.key_invalid_size" I18nErrorKeyInsecure = "user.key_insecure" I18nErrorPrimaryGroup = "user.err_primary_group" I18nErrorDuplicateGroup = "user.err_duplicate_group" I18nErrorNoPermission = "user.no_permissions" I18nErrorNoRootPermission = "user.no_root_permissions" I18nErrorGenericPermission = "user.err_permissions_generic" I18nError2FAInvalid = "user.2fa_invalid" I18nErrorRecoveryCodesInvalid = "user.recovery_codes_invalid" I18nErrorFolderNameRequired = "general.foldername_required" I18nErrorFolderMountPathRequired = "user.folder_path_required" I18nErrorDuplicatedFolders = "user.folder_duplicated" I18nErrorOverlappedFolders = "user.folder_overlapped" I18nErrorFolderQuotaSizeInvalid = "user.folder_quota_size_invalid" I18nErrorFolderQuotaFileInvalid = "user.folder_quota_file_invalid" I18nErrorFolderQuotaInvalid = "user.folder_quota_invalid" I18nErrorPasswordComplexity = "general.err_password_complexity" I18nErrorIPFiltersInvalid = "user.ip_filters_invalid" I18nErrorSourceBWLimitInvalid = "user.src_bw_limits_invalid" I18nErrorFilePatternPathInvalid = "user.file_pattern_path_invalid" I18nErrorFilePatternDuplicated = "user.file_pattern_duplicated" I18nErrorFilePatternInvalid = "user.file_pattern_invalid" I18nErrorDisableActive2FA = "user.disable_active_2fa" I18nErrorPwdChangeConflict = "user.pwd_change_conflict" I18nError2FAConflict = "user.two_factor_conflict" I18nErrorLoginAfterReset = "login.reset_ok_login_error" I18nErrorNameRequired = "general.name_required" I18nErrorInvalidIPMask = "general.allowed_ip_mask_invalid" I18nErrorLoginFromIPDenied = "login.ip_not_allowed" I18nError2FARequired = "login.two_factor_required" I18nError2FARequiredGeneric = "login.two_factor_required_generic" I18nErrorNoOIDCFeature = "general.no_oidc_feature" I18nErrorNoPermissions = "general.no_permissions" I18nErrorPathInvalid = "general.path_invalid" I18nErrorQuotaRead = "general.err_quota_read" I18nErrorEditDir = "general.error_edit_dir" I18nErrorEditSize = "general.error_edit_size" I18nProfileUpdated = "general.profile_updated" I18n2FADisabled = "2fa.disabled" I18nOIDCTokenExpired = "oidc.token_expired" I18nOIDCTokenInvalidAdmin = "oidc.token_invalid_webadmin" I18nOIDCTokenInvalidUser = "oidc.token_invalid_webclient" I18nOIDCErrTokenExchange = "oidc.token_exchange_err" I18nOIDCTokenInvalid = "oidc.token_invalid" I18nOIDCTokenInvalidRoleAdmin = "oidc.role_admin_err" I18nOIDCTokenInvalidRoleUser = "oidc.role_user_err" I18nOIDCErrGetUser = "oidc.get_user_err" I18nErrorInvalidQuotaSize = "user.invalid_quota_size" I18nErrorTimeOfDayInvalid = "user.time_of_day_invalid" I18nErrorTimeOfDayConflict = "user.time_of_day_conflict" I18nErrorInvalidMaxFilesize = "filters.max_upload_size_invalid" I18nErrorInvalidHomeDir = "storage.home_dir_invalid" I18nErrorBucketRequired = "storage.bucket_required" I18nErrorRegionRequired = "storage.region_required" I18nErrorKeyPrefixInvalid = "storage.key_prefix_invalid" I18nErrorULPartSizeInvalid = "storage.ul_part_size_invalid" I18nErrorDLPartSizeInvalid = "storage.dl_part_size_invalid" I18nErrorULConcurrencyInvalid = "storage.ul_concurrency_invalid" I18nErrorDLConcurrencyInvalid = "storage.dl_concurrency_invalid" I18nErrorAccessKeyRequired = "storage.access_key_required" I18nErrorAccessSecretRequired = "storage.access_secret_required" I18nErrorFsCredentialsRequired = "storage.credentials_required" I18nErrorContainerRequired = "storage.container_required" I18nErrorAccountNameRequired = "storage.account_name_required" I18nErrorSASURLInvalid = "storage.sas_url_invalid" I18nErrorPassphraseRequired = "storage.passphrase_required" I18nErrorEndpointInvalid = "storage.endpoint_invalid" I18nErrorEndpointRequired = "storage.endpoint_required" I18nErrorFsUsernameRequired = "storage.username_required" I18nAddGroupTitle = "title.add_group" I18nUpdateGroupTitle = "title.update_group" I18nRoleAddTitle = "title.add_role" I18nRoleUpdateTitle = "title.update_role" I18nErrorInvalidTLSCert = "user.tls_cert_invalid" I18nAddFolderTitle = "title.add_folder" I18nUpdateFolderTitle = "title.update_folder" I18nTemplateFolderTitle = "title.template_folder" I18nErrorDuplicatedUsername = "general.duplicated_username" I18nErrorDuplicatedName = "general.duplicated_name" I18nErrorDuplicatedIPNet = "ip_list.duplicated" I18nErrorRoleAdminPerms = "admin.role_permissions" I18nBackupOK = "maintenance.backup_ok" I18nErrorFolderTemplate = "virtual_folders.template_no_folder" I18nErrorUserTemplate = "user.template_no_user" I18nConfigsOK = "general.configs_saved" I18nOAuth2ErrorVerifyState = "oauth2.auth_verify_error" I18nOAuth2ErrorValidateState = "oauth2.auth_validation_error" I18nOAuth2InvalidState = "oauth2.auth_invalid" I18nOAuth2ErrTokenExchange = "oauth2.token_exchange_err" I18nOAuth2ErrNoRefreshToken = "oauth2.no_refresh_token" I18nOAuth2OK = "oauth2.success" I18nErrorAdminSelfPerms = "admin.self_permissions" I18nErrorAdminSelfDisable = "admin.self_disable" I18nErrorAdminSelfRole = "admin.self_role" I18nErrorIPInvalid = "ip_list.ip_invalid" I18nErrorNetInvalid = "ip_list.net_invalid" I18nFTPTLSDisabled = "status.tls_disabled" I18nFTPTLSExplicit = "status.tls_explicit" I18nFTPTLSImplicit = "status.tls_implicit" I18nFTPTLSMixed = "status.tls_mixed" I18nErrorBackupFile = "maintenance.backup_invalid_file" I18nErrorRestore = "maintenance.restore_error" I18nErrorACMEGeneric = "acme.generic_error" I18nErrorSMTPRequiredFields = "smtp.err_required_fields" I18nErrorClientIDRequired = "oauth2.client_id_required" I18nErrorClientSecretRequired = "oauth2.client_secret_required" I18nErrorRefreshTokenRequired = "oauth2.refresh_token_required" I18nErrorURLRequired = "actions.http_url_required" I18nErrorURLInvalid = "actions.http_url_invalid" I18nErrorHTTPPartNameRequired = "actions.http_part_name_required" I18nErrorHTTPPartBodyRequired = "actions.http_part_body_required" I18nErrorMultipartBody = "actions.http_multipart_body_error" I18nErrorMultipartCType = "actions.http_multipart_ctype_error" I18nErrorPathDuplicated = "actions.path_duplicated" I18nErrorCommandRequired = "actions.command_required" I18nErrorCommandInvalid = "actions.command_invalid" I18nErrorEmailRecipientRequired = "actions.email_recipient_required" I18nErrorEmailSubjectRequired = "actions.email_subject_required" I18nErrorEmailBodyRequired = "actions.email_body_required" I18nErrorRetentionDirRequired = "actions.retention_directory_required" I18nErrorPathRequired = "actions.path_required" I18nErrorSourceDestMatch = "actions.source_dest_different" I18nErrorRootNotAllowed = "actions.root_not_allowed" I18nErrorArchiveNameRequired = "actions.archive_name_required" I18nErrorIDPTemplateRequired = "actions.idp_template_required" I18nActionTypeHTTP = "actions.types.http" I18nActionTypeEmail = "actions.types.email" I18nActionTypeBackup = "actions.types.backup" I18nActionTypeUserQuotaReset = "actions.types.user_quota_reset" I18nActionTypeFolderQuotaReset = "actions.types.folder_quota_reset" I18nActionTypeTransferQuotaReset = "actions.types.transfer_quota_reset" I18nActionTypeDataRetentionCheck = "actions.types.data_retention_check" I18nActionTypeFilesystem = "actions.types.filesystem" I18nActionTypePwdExpirationCheck = "actions.types.password_expiration_check" I18nActionTypeUserExpirationCheck = "actions.types.user_expiration_check" I18nActionTypeUserInactivityCheck = "actions.types.user_inactivity_check" I18nActionTypeIDPCheck = "actions.types.idp_check" I18nActionTypeCommand = "actions.types.command" I18nActionTypeRotateLogs = "actions.types.rotate_logs" I18nActionFsTypeRename = "actions.fs_types.rename" I18nActionFsTypeDelete = "actions.fs_types.delete" I18nActionFsTypePathExists = "actions.fs_types.path_exists" I18nActionFsTypeCompress = "actions.fs_types.compress" I18nActionFsTypeCopy = "actions.fs_types.copy" I18nActionFsTypeCreateDirs = "actions.fs_types.create_dirs" I18nActionThresholdRequired = "actions.inactivity_threshold_required" I18nActionThresholdsInvalid = "actions.inactivity_thresholds_invalid" I18nTriggerFsEvent = "rules.triggers.fs_event" I18nTriggerProviderEvent = "rules.triggers.provider_event" I18nTriggerIPBlockedEvent = "rules.triggers.ip_blocked" I18nTriggerCertificateRenewEvent = "rules.triggers.certificate_renewal" I18nTriggerOnDemandEvent = "rules.triggers.on_demand" I18nTriggerIDPLoginEvent = "rules.triggers.idp_login" I18nTriggerScheduleEvent = "rules.triggers.schedule" I18nErrorInvalidMinSize = "rules.invalid_fs_min_size" I18nErrorInvalidMaxSize = "rules.invalid_fs_max_size" I18nErrorRuleActionRequired = "rules.action_required" I18nErrorRuleFsEventRequired = "rules.fs_event_required" I18nErrorRuleProviderEventRequired = "rules.provider_event_required" I18nErrorRuleScheduleRequired = "rules.schedule_required" I18nErrorRuleScheduleInvalid = "rules.schedule_invalid" I18nErrorRuleDuplicateActions = "rules.duplicate_actions" I18nErrorEvSyncFailureActions = "rules.sync_failure_actions" I18nErrorEvSyncUnsupported = "rules.sync_unsupported" I18nErrorEvSyncUnsupportedFs = "rules.sync_unsupported_fs_event" I18nErrorRuleFailureActionsOnly = "rules.only_failure_actions" I18nErrorRuleSyncActionRequired = "rules.sync_action_required" I18nErrorInvalidPNG = "branding.invalid_png" I18nErrorInvalidPNGSize = "branding.invalid_png_size" I18nErrorInvalidDisclaimerURL = "branding.invalid_disclaimer_url" )
localization id for the Web frontend
const MaxRecursion = 1000
MaxRecursion defines the maximum number of allowed recursions
Variables ¶
var ( ErrValidation = NewValidationError("") ErrNotFound = NewRecordNotFoundError("") ErrMethodDisabled = NewMethodDisabledError("") ErrGeneric = NewGenericError("") ErrRecursionTooDeep = errors.New("recursion too deep") )
errors definitions
var ( // CertsBasePath defines base path for certificates obtained using the built-in ACME protocol. // It is empty is ACME support is disabled CertsBasePath string )
Functions ¶
func ByteCountIEC ¶
ByteCountIEC returns humanized size in IEC (binary) format
func ByteCountSI ¶
ByteCountSI returns humanized size in SI (decimal) format
func BytesToString ¶ added in v2.6.0
BytesToString converts []byte to string without allocations. https://github.com/kubernetes/kubernetes/blob/e4b74dd12fa8cb63c174091d5536a10b8ec19d34/staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go#L278 Use only if strictly required, this method uses unsafe.
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 ¶
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 CleanPathWithBase ¶
CleanPathWithBase returns a clean POSIX (/) absolute path to work with. The specified base will be used if the provided path is not absolute
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 ¶
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 ¶
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 ¶
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 GenerateOpaqueString ¶ added in v2.6.4
func GenerateOpaqueString() string
GenerateOpaqueString generates a cryptographically secure opaque string
func GenerateRSAKeys ¶
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 ¶
GenerateRandomBytes generates random bytes with the specified length
func GetACMECertificateKeyPair ¶ added in v2.5.0
GetACMECertificateKeyPair returns the path to the ACME TLS crt and key for the specified domain
func GetALPNProtocols ¶ added in v2.6.0
GetALPNProtocols returns the ALPN protocols, any invalid protocol will be silently ignored. If no protocol or no valid protocol is provided the default is http/1.1, h2
func GetAbsolutePath ¶ added in v2.4.1
GetAbsolutePath returns an absolute path using the current dir as base if name defines a relative path
func GetDirsForVirtualPath ¶
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 ¶
GetDurationAsString returns a string representation for a time.Duration
func GetHTTPLocalAddress ¶
GetHTTPLocalAddress returns the local address for an http.Request or empty if it cannot be determined
func GetIPFromNetAddr ¶ added in v2.5.0
GetIPFromNetAddr returns the IP from the network address
func GetIPFromRemoteAddress ¶
GetIPFromRemoteAddress returns the IP from the remote address. If the given remote address cannot be parsed it will be returned unchanged
func GetIntFromPointer ¶
GetIntFromPointer returns the int value or zero
func GetLastIPForPrefix ¶ added in v2.5.0
GetLastIPForPrefix returns the last IP for the given prefix https://github.com/go4org/netipx/blob/8449b0a6169f5140fb0340cb4fc0de4c9b281ef6/netipx.go#L173
func GetRealIP ¶
GetRealIP returns the ip address as result of parsing the specified header and using the specified depth
func GetRedactedURL ¶
GetRedactedURL returns the url redacting the password if any
func GetSSHPublicKeyAsString ¶
GetSSHPublicKeyAsString returns an SSH public key serialized as string
func GetStringFromPointer ¶
GetStringFromPointer returns the string value or empty if nil
func GetTLSCiphersFromNames ¶
GetTLSCiphersFromNames returns the TLS ciphers from the specified names
func GetTLSVersion ¶
GetTLSVersion returns the TLS version from an integer value: - 10 means TLS 1.0 - 11 means TLS 1.1 - 12 means TLS 1.2 - 13 means TLS 1.3 default is TLS 1.2
func GetTimeAsMsSinceEpoch ¶
GetTimeAsMsSinceEpoch returns unix timestamp as milliseconds from a time struct
func GetTimeFromMsecSinceEpoch ¶
GetTimeFromMsecSinceEpoch return a time struct from a unix timestamp with millisecond precision
func GetTimeFromPointer ¶
GetTimeFromPointer returns the time value or now
func HTTPListenAndServe ¶
func HTTPListenAndServe(srv *http.Server, address string, port int, isTLS bool, listenerWrapper func(net.Listener) (net.Listener, error), logSender string, ) error
HTTPListenAndServe is a wrapper for ListenAndServe that support both tcp and Unix-domain sockets
func IsByteArrayEmpty ¶
IsByteArrayEmpty return true if the byte array is empty or a new line
func IsDirOverlapped ¶ added in v2.5.0
IsDirOverlapped returns true if dir1 and dir2 overlap
func IsEmailValid ¶
IsEmailValid returns true if the specified email address is valid
func IsFileInputValid ¶
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 IsNameValid ¶ added in v2.7.1
IsNameValid validates that a name/username contains only safe characters. Since names can be used within filesystem paths, only a restricted character set is permitted. Unicode control (Cc), format (Cf) and line/paragraph separator (Zl/Zp) characters, including zero-width, bidirectional and newline-like codepoints, are rejected to prevent invisible, visually confusable names and log injection.
func IsStringPrefixInSlice ¶
IsStringPrefixInSlice searches a string prefix in a slice and returns true if a matching prefix is found
func JSONEscape ¶ added in v2.5.0
JSONEscape returns the JSON escaped format for the input string
func LoadTemplate ¶
LoadTemplate parses the given template paths. It behaves like template.Must but it writes a log before exiting.
func NilIfEmpty ¶
NilIfEmpty returns nil if the input string is empty
func ParseAllowedIPAndRanges ¶
ParseAllowedIPAndRanges returns a list of functions that allow to find if an IP is equal or is contained within the allowed list
func ParseBytes ¶
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 ReadConfigFromFile ¶ added in v2.6.0
ReadConfigFromFile reads a configuration parameter from the specified file
func RemoveDuplicates ¶
RemoveDuplicates returns a new slice removing any duplicate element from the initial one
func SanitizeCSVRow ¶ added in v2.7.2
SanitizeCSVRow neutralizes spreadsheet formula triggers in each value of row, in place, and returns it for convenience.
func SanitizeDomain ¶ added in v2.5.0
SanitizeDomain return the specified domain name in a form suitable to save as file
func SlicesEqual ¶ added in v2.6.3
SlicesEqual checks if the provided slices contain the same elements, also in different order.
func StringToBytes ¶ added in v2.6.0
StringToBytes convert string to []byte without allocations. https://github.com/kubernetes/kubernetes/blob/e4b74dd12fa8cb63c174091d5536a10b8ec19d34/staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go#L289 Use only if strictly required, this method uses unsafe.
func VerifyFileChecksum ¶ added in v2.7.1
VerifyFileChecksum computes the hash of the given file using the provided hash algorithm and compares it against the expected checksum (in hex format). It returns an error if the checksum does not match or if the operation fails.
Types ¶
type GenericError ¶
type GenericError struct {
// contains filtered or unexported fields
}
GenericError raised for not well categorized error
func NewGenericError ¶
func NewGenericError(errorString string) *GenericError
NewGenericError returns a generic error
func (*GenericError) Error ¶
func (e *GenericError) Error() string
func (*GenericError) Is ¶ added in v2.5.0
func (e *GenericError) Is(target error) bool
Is reports if target matches
type I18nError ¶ added in v2.6.0
type I18nError struct {
Message string
// contains filtered or unexported fields
}
I18nError is an error wrapper that add a message to use for localization.
func NewI18nError ¶ added in v2.6.0
func NewI18nError(err error, message string, options ...I18nErrorOption) *I18nError
NewI18nError returns a I18nError wrappring the provided error
type I18nErrorOption ¶ added in v2.6.0
type I18nErrorOption func(*I18nError)
I18nErrorOption defines a functional option type that allows to configure the I18nError.
func I18nErrorArgs ¶ added in v2.6.0
func I18nErrorArgs(args map[string]any) I18nErrorOption
I18nErrorArgs is a functional option to set I18nError arguments.
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(errorString string) *MethodDisabledError
NewMethodDisabledError returns a method disabled error
func (*MethodDisabledError) Error ¶
func (e *MethodDisabledError) Error() string
Method disabled error details
func (*MethodDisabledError) Is ¶ added in v2.5.0
func (e *MethodDisabledError) Is(target error) bool
Is reports if target matches
type RecordNotFoundError ¶
type RecordNotFoundError struct {
// contains filtered or unexported fields
}
RecordNotFoundError raised if a requested object is not found
func NewRecordNotFoundError ¶
func NewRecordNotFoundError(errorString string) *RecordNotFoundError
NewRecordNotFoundError returns a not found error
func (*RecordNotFoundError) Error ¶
func (e *RecordNotFoundError) Error() string
func (*RecordNotFoundError) Is ¶ added in v2.4.4
func (e *RecordNotFoundError) Is(target error) bool
Is reports if target matches
type ValidationError ¶
type ValidationError struct {
// contains filtered or unexported fields
}
ValidationError raised if input data is not valid
func NewValidationError ¶
func NewValidationError(errorString string) *ValidationError
NewValidationError returns a validation errors
func (*ValidationError) GetErrorString ¶
func (e *ValidationError) GetErrorString() string
GetErrorString returns the unmodified error string
func (*ValidationError) Is ¶ added in v2.5.0
func (e *ValidationError) Is(target error) bool
Is reports if target matches