funcs

package
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2024 License: MulanPSL-2.0 Imports: 53 Imported by: 0

Documentation

Index

Constants

View Source
const AUTHCODE_KEY_DEFAULT = "abcdefghijklmnopqrstuvwxyz1234567890"
View Source
const HTTP_CONTENT_TYPE_JSON string = "application/json"
View Source
const HTTP_TIMEOUT_DEFAULT time.Duration = time.Second * 10
View Source
const OS_LINUX = "linux"
View Source
const OS_WIN = "windows"

Variables

View Source
var MATCH_ALL_CAP = regexp.MustCompile("([a-z0-9])([A-Z])")
View Source
var MATCH_FIRST_CAP = regexp.MustCompile("(.)([A-Z][a-z]+)")
View Source
var MATCH_NON_ALPHA_NUMERIC = regexp.MustCompile(`[^a-zA-Z0-9]+`)
View Source
var MaxDecryptBlock = 128

MaxDecryptBlock rsa decode max length

View Source
var MaxEncryptBlock = 117

MaxEncryptBlock rsa encode max length

Functions

func AbsolutePath

func AbsolutePath() (string, error)

AbsolutePath get execute binary path

func AppIs64Bit

func AppIs64Bit() bool

本软件是否64位

func Assert

func Assert(condition bool, msg string, code ...int)

Assert 条件断言 当断言条件为 假 时触发 panic 对于当前请求不会再执行接下来的代码,并且返回指定格式的错误信息和错误码

func Authcode

func Authcode(text string, params AuthcodeParam) (str string, err error)

Authcode Discuz Authcode golang version

func Base64Decode

func Base64Decode(str string) ([]byte, error)

Base64Decode string decode

func Base64Encode

func Base64Encode(b []byte) string

Base64Encode string encode

func CheckErr

func CheckErr(err error)

func CheckFileIsExist

func CheckFileIsExist(filename string) bool

func CheckGISPointInArea

func CheckGISPointInArea(areaString string, pointLng string, pointLat string) bool

func CheckRunnable

func CheckRunnable(err error, runnable *bool)

func CompareHashAndPassword

func CompareHashAndPassword(e string, p string) (bool, error)

func Contain

func Contain(obj interface{}, target interface{}) (bool, error)

判断某个元素是否在 slice, array, map 中

func ContainsInterface added in v1.0.6

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

Contains item is in map/slice/array

func ConvertGBKToUTF8

func ConvertGBKToUTF8(src string, srcCode string, tagCode string) string

func CopyFile

func CopyFile(srcName, dstName string) (written int64, err error)

*

  • 复制文件

func DateFormat

func DateFormat(format string, t time.Time) string

DateFormat format time.Time

func EnvAddPathFromRoot

func EnvAddPathFromRoot(path string)

环境变量 - 添加PATH, PATH不本应用运行目录下的子目录

func Exists

func Exists(path string) bool

Exists whether file or directory exists

func FormatTimeStr

func FormatTimeStr(timeStr string) (string, error)

func GbkToUtf8 added in v1.0.6

func GbkToUtf8(s []byte) ([]byte, error)

func GetCurrentTime

func GetCurrentTime() time.Time

func GetCurrentTimeStr

func GetCurrentTimeStr() string

func GetIpFromAddress

func GetIpFromAddress(addr string) string

func GetLocaHonst

func GetLocaHonst() string

获取局域网ip地址

func GetLocalIP

func GetLocalIP() ([]string, error)

GetLocalIP get local network ip

func GetLocation

func GetLocation(ip string) string

获取外网ip地址

func GetPortFromAddress

func GetPortFromAddress(addr string) int

func Getwd

func Getwd() string

func HMacSHA256

func HMacSHA256(s, key string) string

HMacSHA256 hmac sha256

func HTTPRequest

func HTTPRequest(url string, method Method, args ...interface{}) (string, error)

HTTPRequest request url request url method request method post or get args[0] type is map[string]string or string, request paramaters, \x00@ if upload file args[1] type is map[string]string, request headers args[2] type is bool, whether to return the result args[3] type is *http.Client, custom client

func HasError

func HasError(err error, msg string, code ...int)

HasError 错误断言 当 error 不为 nil 时触发 panic 对于当前请求不会再执行接下来的代码,并且返回指定格式的错误信息和错误码 若 msg 为空,则默认为 error 中的内容

func HttpGet

func HttpGet(url string) (string, error)

func HttpGetHttpCode

func HttpGetHttpCode(url string) (int, error)

func HttpPost added in v1.0.2

func HttpPost(url string, contentType string, body []byte) (string, error)

func HttpPostUseHandle added in v1.0.6

func HttpPostUseHandle(url string, body []byte, httpRequestHandler HttpRequestHandler) (string, error)

发启HTTP请求, 可以使用请求处理器对请求进行一些初始化操作, 比如设置头部信息等

func IP2Long

func IP2Long(ipstr string) (uint64, error)

IP2Long IP convert to long int

func IdsStrToIdsIntGroup

func IdsStrToIdsIntGroup(key string, c *gin.Context) []int

获取URL中批量id并解析

func If

func If[T any](condition bool, trueVal, falseVal T) T

请注意它不能完全替代三元表达式, trueVal 和 falseVal 必须计算出来, 这意味着 If(len(list) > 0, list[0], 0) 这样使用时会因为 list 为空而产生异常

func IndexOf

func IndexOf(obj interface{}, target interface{}) (int, error)

从 slice, array 中找到指定元素的索引 obj: 要查找的元素 target: 要查找的slice, array 成功时返回 索引, nil 失败时返回 -1, 错误

func Int64Abs

func Int64Abs(n int64) int64

func Int64ToString

func Int64ToString(e int64) string

func IntAbs

func IntAbs(n int) int

func IntToString

func IntToString(e int) string

func IsDateTime

func IsDateTime(dateTimeStr string) bool

暂时不能用, 验证失败

func IsDir

func IsDir(path string) bool

IsDir return bool

func IsEmpty

func IsEmpty(val interface{}) (b bool)

IsEmpty true: nil, "", false, 0, 0.0, {}, []

func IsFile

func IsFile(path string) bool

IsFile return tool

func IsIP

func IsIP(ip string) bool

IsIP ip address is valid

func IsMac

func IsMac(mac string) bool

IsMac mac address is valid

func IsMobile

func IsMobile(mobile string) bool

IsMobile check chinese mobile number

func IsNotEmpty

func IsNotEmpty(val interface{}) (b bool)

func IsPointInsidePolygon

func IsPointInsidePolygon(point gisPoint, polygon []gisPoint) bool

func IsProcessRunning added in v1.0.6

func IsProcessRunning(pid int) bool

判断进程是否存在

func IsProcessRunningLinux added in v1.0.6

func IsProcessRunningLinux(pid int) bool

判断进程是否存在

func IsProcessRunningWin added in v1.0.6

func IsProcessRunningWin(pid int) bool

func Keys

func Keys(m map[string]interface{}) []string

Keys key of map

func LcFirst added in v1.0.7

func LcFirst(str string) string

首字母小写

func LogAsJson

func LogAsJson(v any)

func LogIfError

func LogIfError(err error)

func LogListAsJson

func LogListAsJson(vList []any)

func Long2IP

func Long2IP(ip uint32) string

Long2IP longint convert to IP

func MakeDirs

func MakeDirs(path string) error

*

  • 生成多级目录, 目录属性默认设为 os.ModePerm *
  • @param path 目录, 可支持多级目录 *

func MapKeyToSnakeCase added in v1.0.7

func MapKeyToSnakeCase(fromMap map[string]any) map[string]any

map 里的key从驼峰转下划线 主要用于查询条件转成实际数据库字段名

func MapToOrderedMap added in v1.0.2

func MapToOrderedMap(input map[string]interface{}) *orderedmap.OrderedMap

普通的MAP转换成有序MAP(顺手按KEY升序排序)

func Md5Sum

func Md5Sum(text string) string

Md5Sum md5

func Md5V

func Md5V(str string) string

func NewGISArea

func NewGISArea(points []gisPoint) *gisArea

实例化一个面

func NewRand

func NewRand() *rand.Rand

NewRand return *rand.Rand

func Now

func Now(f ...int) string

Now format now

func NumberCompare

func NumberCompare[T number](arg1, arg2 T) int

数字比较, 相等返回 0; arg1大于arg2返回 1; arg1小于arg2返回 -1;

func NumberEQ

func NumberEQ[T number](arg1, arg2 T) bool

数字比较, arg1是否大于arg2

func NumberGT

func NumberGT[T number](arg1, arg2 T) bool

数字比较, arg1是否大于arg2

func NumberLT

func NumberLT[T number](arg1, arg2 T) bool

数字比较, arg1是否小于arg2

func NumberNGT

func NumberNGT[T number](arg1, arg2 T) bool

数字比较, arg1是否不大于arg2

func NumberNLT

func NumberNLT[T number](arg1, arg2 T) bool

数字比较, arg1是否不小于arg2

func PrintAsJson

func PrintAsJson(v any)

func PrintIfError

func PrintIfError(err error)

func PrintListAsJson

func PrintListAsJson(vList []any)

func QueryFetchConditionMap added in v1.0.7

func QueryFetchConditionMap(query any, conditionMap map[string]interface{})

从 查询条件 生成查询 map 一般用于生成查询条件, 给GORM的 Where() 用 query结构体每个属性都设置成指针类型 属性值不为空的就说明此属性的值要做为查询条件, 会被放到生成的 map 里 WARNING: 会忽略不是指针类型的字段, 如果要做到更灵活, 以后再扩展

func RSADecode

func RSADecode(b, key []byte, t ...CertType) ([]byte, error)

RSADecode rsa decode

func RSAEncode

func RSAEncode(b, key []byte, t ...CertType) ([]byte, error)

RSAEncode rsa

func RandArray

func RandArray(arr []string) string

RandArray rand string slice

func RandRangeInt

func RandRangeInt(min, max int) int

RandRangeInt return min<=x<max

func RandRangeInt32

func RandRangeInt32(min, max int32) int32

RandRangeInt32 return min<=x<max

func RandomInt

func RandomInt(min, max int) int

Returns an int >= min, < max

func RandomStr

func RandomStr(length int) string

RandomStr 随机生成字符串

func RangeArray

func RangeArray(m, n int) (b []int)

RangeArray generate array

func ReadFileAll

func ReadFileAll(filename string) (content []byte, err error)

func ReflectCopyProperties added in v1.0.6

func ReflectCopyProperties(dst, src interface{}) (err error)

属性复制

func ReflectGetFieldValue added in v1.0.6

func ReflectGetFieldValue[T any](data interface{}, fieldName string) T

获取指定属性的值

func ReflectSetFieldValue added in v1.0.6

func ReflectSetFieldValue[T any](dst interface{}, fieldName string, value T) error

设置指定属性的值

func RemoveFilesWildCard

func RemoveFilesWildCard(filesWildCard string)

*

  • 带通配符删除文件

func Reverse

func Reverse(s string) string

Reverse string reverse

func RootPath

func RootPath() string

func RsaDecode

func RsaDecode(b, rsaKey []byte, t ...CertType) ([]byte, error)

RsaDecode rsa decode

func RsaEncode

func RsaEncode(b, rsaKey []byte, t ...CertType) ([]byte, error)

RsaEncode rsa encode

func SHA256

func SHA256(s string) string

SHA256 return string

func SaveImageDataToFileAutoType

func SaveImageDataToFileAutoType(imageFile string, imageData image.Image) error

保存 image.Image 数据到图片文件, 将用 go 官方的图片数据解析器自动判断数据格式, 也会用文件扩展名自动存成相应的图片类型

func SecondsToTimeFormat added in v1.0.7

func SecondsToTimeFormat(seconds, f int) (timeStr string)

秒数转换成具体的时间

func SliceContains added in v1.0.6

func SliceContains[T comparable](s []T, e T) bool

func SliceCovertToInterface added in v1.0.6

func SliceCovertToInterface[T any](sliceToCovert []T) []interface{}

func SliceCovertToMap added in v1.0.6

func SliceCovertToMap[KEY_TYPE comparable, DATA_TYPE any](sliceToCovert []DATA_TYPE, keyName string) map[KEY_TYPE]DATA_TYPE

切片 转换成 map 一般用于快速找到特定数据 比如查询出来的数据列表, 用ID做 map 的 key 使用者可以很方便的找到 ID 对应的数据 不需要去遍历整个列表

func SliceFilter

func SliceFilter[T SliceType](sliceToFilter []T, filterFunc func(item T) bool) []T

func SliceGetEnd

func SliceGetEnd[T any](list []T) T

func SliceRemoveDuplicateElement added in v1.0.6

func SliceRemoveDuplicateElement[T SliceType](sliceToRemoveDuplicate []T) []T

func Split

func Split(str, match string) []string

Split split by match

func SplitBySpaceTab

func SplitBySpaceTab(str string) []string

SplitBySpaceTab splite by space or tab

func StrTimeDifferenceSeconds added in v1.0.7

func StrTimeDifferenceSeconds(strTime1, strTime2 string) (difference int, err error)

两个字符串时期的时间差(秒)

func StrToInt

func StrToInt(err error, index string) int

不建议使用的方法(即将过时) Deprecated method (out of date)

func StrToLocalTime

func StrToLocalTime(value string) (time.Time, error)

StrToLocalTime get time.Time from string

func StrToSnakeCase added in v1.0.6

func StrToSnakeCase(str string) string

驼峰转下划线

func StrToTime

func StrToTime(value string, zone ...bool) (time.Time, error)

StrToTime get time.Time from string

func StringIsEmpty

func StringIsEmpty(str string) bool

func StringToBool

func StringToBool(e string) (bool, error)

func StringToFloat64

func StringToFloat64(e string) (float64, error)

字符串转float64

func StringToFloat64NotError

func StringToFloat64NotError(e string) float64

字符串转float64, 不检测是否错误

func StringToInt

func StringToInt(e string) (int, error)

func StringToInt64

func StringToInt64(e string) (int64, error)

func StringToInt64NotError added in v1.0.7

func StringToInt64NotError(e string) int64

字符串转 int64, 不检测是否错误

func StringToIntNotError added in v1.0.7

func StringToIntNotError(e string) int

字符串转 int, 不检测是否错误

func StringToUInt64 added in v1.0.7

func StringToUInt64(e string) (uint64, error)

func StringToUInt64NotError added in v1.0.7

func StringToUInt64NotError(e string) uint64

字符串转 uint64, 不检测是否错误

func StructToJsonStr

func StructToJsonStr(e interface{}) (string, error)

func StructToMap

func StructToMap(item interface{}) map[string]interface{}

StructToMap struct convert to map

func StructToOrderedMap added in v1.0.2

func StructToOrderedMap(input interface{}) *orderedmap.OrderedMap

结构体转换成有序MAP(顺手按KEY升序排序)

func StructToStringMap added in v1.0.2

func StructToStringMap(input interface{}) map[string]interface{}

结构体转换成MAP

func TimeFormat

func TimeFormat(t time.Time, f int) (timeStr string)

TimeFormat format time.Time

func TimeToSecond

func TimeToSecond(timeStr string) int

时间转成秒数, 用来作当天的工作安排类的计算, 比如 time 为 1:00 , 结果为 60 秒 支持 xx:xx:xx 和 xx:xx

func ToCamelCase added in v1.0.6

func ToCamelCase(s string) string

下划线转小驼峰

func ToCamelCaseUcFirst added in v1.0.7

func ToCamelCaseUcFirst(str string) string

下划线转大驼峰

func TodayDate

func TodayDate() string

获取今天的日期, 格式 1979-01-01

func Trim

func Trim(str string) string

Trim remove "", \r, \t, \n

func URLDecode

func URLDecode(str string) (string, error)

URLDecode urldecode

func URLEncode

func URLEncode(params interface{}) string

URLEncode urlencode

func UUID

func UUID() (string, error)

UUID uuid

func UcFirst added in v1.0.7

func UcFirst(str string) string

首字母大写

func UintptrToString

func UintptrToString(stringPtr uintptr) string

从指定的内存地址取出字符串 过程: 一个个字节取出, 直到为 0 值结束

func UintptrToUTF8String

func UintptrToUTF8String(stringPtr uintptr) string

从指定的内存地址取出UTF8字符串

func UnZipFirstFile added in v1.0.6

func UnZipFirstFile(zipFile string) ([]byte, error)

解压zip文件里第一个文件(用于只压缩了一个文件的zip包, 经常会碰到, 避免再输入文件名)

func Utf8ToGbk added in v1.0.6

func Utf8ToGbk(s []byte) ([]byte, error)

func ValidateIsEmpty

func ValidateIsEmpty(a interface{}) bool

TODO: 验证会不会比 IsEmpty() 好用

func Values

func Values(m map[string]interface{}) []interface{}

Values value of map

func WeekDayIdx

func WeekDayIdx(date string) int

获取日期是周几的索引, 星期天为0, 失败时返回 -1

func WeekDayIdxForHuman

func WeekDayIdxForHuman(date string) int

获取日期是周几的索引, 以普通人的阅读方式返回索引, 星期一为1, 星期天为7, 失败时返回 -1

func WriteFile

func WriteFile(fileFullName string, content []byte) error

*

  • 以覆盖的方式写文件, 文件不存在时自动创建属性默认设为 0644 *
  • @param fileName 文件名
  • @param content 文件内容 *
  • @return 错误信息

func YesterdayDate

func YesterdayDate() string

获取昨天的日期, 格式 1978-12-31

func ZipContent added in v1.0.6

func ZipContent(zipFile string, fileName string, content []byte) error

将指定目录下的所有文件压缩成一个zip文件

func ZipDirFiles added in v1.0.6

func ZipDirFiles(zipFile, dir string) error

将指定目录下的所有文件压缩成一个zip文件

Types

type AuthCodeType

type AuthCodeType int

AuthCodeType auth code type

const (
	// ENCODE encode str
	AUTHCODE_TYPE_ENCODE AuthCodeType = iota
	// DECODE decode str
	AUTHCODE_TYPE_DECODE
)

type AuthcodeParam

type AuthcodeParam struct {
	EncryptOrDecrypt AuthCodeType // 加密还是解密
	Key              string       // 密钥
	Expires          uint         // 过期时间, 秒
	DynamicLen       uint         // 动态码长度
}

type CertType

type CertType int

CertType Certificate type

const (
	// PKCS1 CertType
	PKCS1 CertType = iota
	// PKCS8 CertType
	PKCS8
)

type HttpRequestHandler added in v1.0.6

type HttpRequestHandler func(*http.Request)

type Method

type Method int8

Method http request method

const (
	// POST post http request
	POST Method = iota
	// GET http request get method
	GET
)

func (Method) String

func (m Method) String() string

type SliceType

type SliceType interface{ comparable }

Jump to

Keyboard shortcuts

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