utils

package module
v1.0.12 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2022 License: MIT Imports: 23 Imported by: 4

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrorNotADirectory = errors.New("not a directory")
)

errors

Functions

func AppendFile

func AppendFile(path string) (*os.File, error)

AppendFile with given path

func BackupFileName

func BackupFileName(path, extension string) string

BackupFileName returns a new name for inputFileName and backup extension, also checking the existence of other bak files with intention not to overwrite it when renaming to new name

func CallerFuncName

func CallerFuncName() (string, error)

CallerFuncName returns name of a func which is a caller for func from which CallerFuncName was called

func CallerFuncNameString

func CallerFuncNameString() string

CallerFuncNameString returns a string from CallerFuncName

func CallerFuncNameStringWithOffset added in v1.0.11

func CallerFuncNameStringWithOffset(i int) string

CallerFuncNameStringWithOffset returns a string from CallerFuncNameWithOffset

func CallerFuncNameWithOffset added in v1.0.11

func CallerFuncNameWithOffset(i int) (string, error)

CallerFuncNameWithOffset works like CallerFuncName but skips additional i stack frames

func CheckSnils

func CheckSnils(snils string) (bool, error)

CheckSnils проверяет СНИЛС на валидность путём вычисления его контрольной суммы

func CircularAdd

func CircularAdd(a int, max int) int

CircularAdd возвращает следующий элемент кольцевой целочисленной арифметики начиная от a, макс. элемент равен max

func CountElementsOnPage

func CountElementsOnPage(elementsTotal uint, page uint, pageSize uint) uint

CountElementsOnPage возвращает количество элементов на заданной странице page с размером pageSize если всего элементов elementsTotal. Если pageSize равно 0, считается что оно равно elementsTotal

func CountPages

func CountPages(elementsTotal uint, pageSize uint) uint

CountPages возвращает количство страниц размера pageSize если всего элементов elementsTotal. Если pageSize равно 0, возвращает 1

func EncodeToWindows1251

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

EncodeToWindows1251 перекодирует срез байт b из стандартной Go кодировки UTF-8 в кодировку Windows-1251

func FileExists

func FileExists(path string) bool

FileExists returns true if a file with given path exists

func FileSize

func FileSize(path string) int64

FileSize returns size of a file with given path, it returns 0 if file doesn't exists or on error

func FormatPhone

func FormatPhone(phone string) (string, error)

FormatPhone форматирует строку с номером телефона в формат "71234567890" Возвращает: Успех: Форматированный номер телефона, nil Ошибка: Исходный номер телефона, ошибка

func GetFunctionName

func GetFunctionName(function interface{}) (string, error)

GetFunctionName returns a name of function

func GetIPAddress

func GetIPAddress(request *http.Request) string

GetIPAddress пытается получить IP адрес из заголовков HTTP возвращает соотв-ю строку, или "0.0.0.0"

func GetSelfPath

func GetSelfPath() (string, error)

GetSelfPath returns a path to the caller executable

func IsDir

func IsDir(path string) (bool, error)

IsDir returns true if the path specified is a directory

func IsEmptyDir added in v1.0.6

func IsEmptyDir(path string) (bool, error)

IsEmptyDir returns true if the path specified is an empty directory

func IsInDocker added in v1.0.7

func IsInDocker() bool

IsInDocker returns whether execution is going inside a Docker container

func IsInGitlab added in v1.0.8

func IsInGitlab() bool

IsInGitlab returns true if we are in Gitlab

func IsInVexor

func IsInVexor() bool

IsInVexor returns whether execution is going inside Vexor CI

func IsNil

func IsNil(obj interface{}) bool

IsNil returns true if obj is nil or contains empty value, otherwise returns false

func MarshalUnmarshalJSON added in v1.0.2

func MarshalUnmarshalJSON(data, out interface{}) error

MarshalUnmarshalJSON marshals data to JSON and unmarshal it to out. Useful to convert interface{} to something more concrete via JSON

func MustMarshalJSON added in v1.0.12

func MustMarshalJSON(data interface{}) []byte

MustMarshalJSON works as json.Marshal, but panics on error

func MustMarshalUnmarshalJSON added in v1.0.5

func MustMarshalUnmarshalJSON(data, out interface{})

MustMarshalUnmarshalJSON works like MarshalUnmarshalJSON but panic on error

func MustSelfPath

func MustSelfPath() string

MustSelfPath returns path to this application executable, it panic at error

func NewFileUploadRequest

func NewFileUploadRequest(req FileUploadRequest) (*http.Request, error)

NewFileUploadRequest creates a new file upload HTTP request with optional extra params

func PBool

func PBool(b bool) *bool

PBool returns a pointer to bool value b

func PInt

func PInt(i int) *int

PInt returns a pointer to int value i

func PString

func PString(s string) *string

PString returns a pointer to string s

func PUint

func PUint(i uint) *uint

PUint returns a pointer to uint value i

func RemoveDuplicates

func RemoveDuplicates(slice interface{}) (interface{}, bool, error)

RemoveDuplicates returns a slice with duplicates removed. It omits NaN values and returns true in second parameter if a NaN value were found.

func RenderFloat

func RenderFloat(format string, n float64) (string, error)

todo документация

func RenderInteger

func RenderInteger(format string, n int64) (string, error)

todo document it

func Round

func Round(val float64, roundOn float64, places int) float64

Round округляет значение val. Возвращает округлённое значение. Параметр roundOn задаёт значение разряда, по которому определяется вид округления - в большую или в меньшую сторону. Параметр places определяет количество знаков после десятичной точки, в случае, если он положителен, до целых - если 0. Может быть отрицательным, в этом случае, например, при -1 округление выполняется до десятков. Примеры: Round(2.34, .5, 1) возвращает 2.3 Round(2.37, .5, 1) возвращает 2.4 Round(2.37, .5, 0) возвращает 2.0 Round(2.77, .5, 0) возвращает 3.0

func SliceContains

func SliceContains(needle interface{}, haystack interface{}) bool

SliceContains checks for value of needle in slice haystack haystack's underlying type should be a slice, if not, the function panics

func SliceIntersects added in v1.0.10

func SliceIntersects(a, b interface{}) bool

SliceIntersects returns whether two slices intersects

func SortUints

func SortUints(a []uint)

SortUints sorts a slice of uints in increasing order.

func StringSliceSubstract added in v1.0.9

func StringSliceSubstract(a, b []string) []string

StringSliceSubstract substracts b from a, working with slices of strings

func StringToStringSlice

func StringToStringSlice(s, sep string) []string

StringToStringSlice converts a string values separated by sep to slice of string elements empty elements are ignored

func StringToUint

func StringToUint(s string) (uint, error)

StringToUint interpretes string as a value of type uint

func StringToUintSlice

func StringToUintSlice(s string, sep string, min uint) ([]uint, error)

StringToUintSlice converts a string values separated by sep to slice of uint elements It returns an error if any element can't be converted to uint If a converted element is less than min, it will not be added empty elements are ignored

func SubstringBetween

func SubstringBetween(s, l, r string) string

SubstringBetween returns a substring between substrs l and r from source string s

func ToLowerFirstRune

func ToLowerFirstRune(s string) string

ToLowerFirstRune returns string s with first rune converted to it's lowercase form

func Try

func Try(actionFunc func() error, n int, delay time.Duration, conditionFunc func(e error) bool) (int, error)

Try tries n times to call an actionFunc() until conditionFunc() returns true actionFunc is a func returning error n is a number of times to try to call actionFunc() delay is a delay between calls actionFunc() conditionFunc is a func accepting error, if it returns true, Try will try again Try returns a number of attempts

func UintsAreSorted

func UintsAreSorted(a []uint) bool

UintsAreSorted tests whether a slice of uints is sorted in increasing order.

func UniqID

func UniqID(n int) (string, error)

UniqID creates a random string with length n

Types

type FileUploadRequest

type FileUploadRequest struct {
	Uri      string            // uri to send request
	Params   map[string]string // additional parameters or nil, would be written into request fields
	Key      string            // key of multipart field
	Data     []byte            // file data
	FileName string            // file name
}

FileUploadRequest это параметры для POST запроса с файлом

type IndicesSlice

type IndicesSlice struct {
	sort.Interface
	Indices []int
}

IndicesSlice is a type for sorting with indexes remembering

func NewIndicesSlice

func NewIndicesSlice(n sort.Interface) *IndicesSlice

NewIndicesSlice creates new slice for sorting with indices remembering

func NewIndicesUintSlice

func NewIndicesUintSlice(n ...uint) *IndicesSlice

NewIndicesUintSlice creates new slice of uint type for sorting with indices remembering

func (IndicesSlice) Swap

func (s IndicesSlice) Swap(i, j int)

Swap reimplements Swap() for sort.Interface

type StringSlice

type StringSlice []string

StringSlice это срез строк реализует интерфейс Stringer

func (StringSlice) String

func (ss StringSlice) String() string

String возвращает строку, содержащую значения среза строк, где элементы разделены переносами строки

type UintSlice

type UintSlice []uint

UintSlice attaches the methods of sort.Interface to []uint, sorting in increasing order.

func (UintSlice) Len

func (p UintSlice) Len() int

func (UintSlice) Less

func (p UintSlice) Less(i, j int) bool

func (UintSlice) Sort

func (p UintSlice) Sort()

func (UintSlice) Swap

func (p UintSlice) Swap(i, j int)

Directories

Path Synopsis
zip

Jump to

Keyboard shortcuts

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