gox

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2020 License: Apache-2.0 Imports: 26 Imported by: 0

README

gox

Golang的基础库,提供各种便捷的方法,包括

  • 字符串
  • 配置
  • 时间处理
  • 基础类型

Documentation

Index

Constants

View Source
const (
	DefaultTimeLayout = "2006-01-02 15:04:05"

	// 时间常量
	// 一天
	Day = 24 * time.Hour
	// 一周
	Week = 7 * Day
	// 一个月
	Month = 30 * Day
	// 一年
	Year = 365 * Day
)
View Source
const (
	HeaderContentType = "Content-Type"
)

Variables

View Source
var (
	ErrOnCopySelf   = &CodeError{ErrorCode: 1001, Msg: "不能复制或者移动自身"}
	ErrSrcIsNotFile = &CodeError{ErrorCode: 1002, Msg: "源文件不是文件"}
)
View Source
var (
	// Separate nested key components with dots, e.g. "a.b.1.c.d"
	DotStyle = SeparatorStyle{Middle: "."}

	// Separate with path-like slashes, e.g. a/b/1/c/d
	PathStyle = SeparatorStyle{Middle: "/"}

	// Separate ala Rails, e.g. "a[b][c][1][d]"
	RailsStyle = SeparatorStyle{Before: "[", After: "]"}

	// Separate with underscores, e.g. "a_b_1_c_d"
	UnderscoreStyle = SeparatorStyle{Middle: "_"}
)

Default styles

View Source
var (
	// Epoch is set to the twitter snowflake epoch of Nov 04 2010 01:42:54 UTC in milliseconds
	// You may customize this to set a different epoch for your application.
	Epoch int64 = 1288834974657

	// NodeBits holds the number of bits to use for Snowflake
	// Remember, you have a total 22 bits to share between Snowflake/Step
	NodeBits uint8 = 10

	// StepBits holds the number of bits to use for Step
	// Remember, you have a total 22 bits to share between Snowflake/Step
	StepBits uint8 = 12
)
View Source
var ErrInvalidBase32 = errors.New("invalid base32")

ErrInvalidBase32 is returned by ParseBase32 when given an invalid []byte

View Source
var ErrInvalidBase58 = errors.New("invalid base58")

ErrInvalidBase58 is returned by ParseBase58 when given an invalid []byte

View Source
var NotValidInputError = errors.New("Not a valid input: map or slice")

Nested input must be a map or slice

View Source
var NotValidJsonInputError = errors.New("Not a valid input, must be a map")

JSON nested input must be a map

Functions

func CamelName

func CamelName(name string) string

下划线写法转为驼峰写法

func CheckPasswordHash

func CheckPasswordHash(password, hash string) bool

CheckPasswordHash 检查密码的正确性

func Contract

func Contract(separator string, strings ...string) (result string)

func CopyFile added in v1.2.0

func CopyFile(src, dst string) (copyFiles []string, err error)

func CreateDir added in v1.2.0

func CreateDir(dirName string) error

func CreateFile added in v1.2.0

func CreateFile(file string) error

func DeleteFile added in v1.2.0

func DeleteFile(src string) (err error)

DeleteFile 删除的文件

func DirNotExistCreate added in v1.2.0

func DirNotExistCreate(path string) (err error)

DirNotExistCreate err为空存在,不会空则

func Flatten

func Flatten(nested map[string]interface{}, prefix string, style SeparatorStyle) (map[string]interface{}, error)

Flatten generates a flat map from a nested one. The original may include values of type map, slice and scalar, but not struct. Keys in the flat map will be a compound of descending map keys and slice iterations. The presentation of keys is set by style. A prefix is joined to each key.

func FlattenString

func FlattenString(nestedStr, prefix string, style SeparatorStyle) (string, error)

FlattenString generates a flat JSON map from a nested one. Keys in the flat map will be a compound of descending map keys and slice iterations. The presentation of keys is set by style. A prefix is joined to each key.

func GetAllFilesBy added in v1.2.0

func GetAllFilesBy(pathName string, ty FileType) (allFiles []string, err error)

func GetContentType added in v1.2.0

func GetContentType(filepath string) (contentType string, err error)

GetContentType 获得文件的ContentType

func GetDirFatherDeep added in v1.2.0

func GetDirFatherDeep(dir string) int

GetDirFatherDeep dir以/开头

func GetDirSonDeep added in v1.2.0

func GetDirSonDeep(dir string) int

func GetFileContentType added in v1.2.0

func GetFileContentType(file *os.File) (contentType string, err error)

GetFileContentType 获得文件的ContentType

func GetFileDir added in v1.2.0

func GetFileDir(filePath string) string

GetFileDir 获得文件的目录形式

func GetFileName added in v1.2.0

func GetFileName(filePath string) string

GetFileName 获得文件名

func GetFileNameWithExt added in v1.2.0

func GetFileNameWithExt(filePath string, ext string) (path string)

GetFileNameWithExt 获得带扩展名的文件名

func GetNeedDeleteFiles added in v1.2.0

func GetNeedDeleteFiles(src string) (deleteFiles []string, err error)

func HashPassword

func HashPassword(password string) (string, error)

HashPassword 生成密码

func HashPasswordWithCost

func HashPasswordWithCost(password string, cost int) (string, error)

HashPasswordWithCost 生成密码

func InitialLowercase

func InitialLowercase(from string) (to string)

InitialLowercase 首字母小写

func IsDir added in v1.2.0

func IsDir(path string) (bool, error)

IsDir 判断所给路径是否为文件夹

func IsFileExist added in v1.2.0

func IsFileExist(filename string) bool

IsFileExist 判断文件是否存在

func IsInArray

func IsInArray(val interface{}, array interface{}) (exists bool, index int)

IsInArray 通用的判断数据是否在数组中

func JSONString

func JSONString(obj interface{}) string

JSONString 转换成JSON字符串

func ListDir added in v1.2.0

func ListDir(src string) (infos []string, err error)

func Md5

func Md5(from string) (to string, err error)

Md5 将字符串加密成Md5字符串

func MoveFile added in v1.2.0

func MoveFile(src, dst string) (err error)

func MySQLJsonUpdate

func MySQLJsonUpdate(
	table string, filed string,
	conditionFiled string, conditionValue interface{},
	data map[string]interface{},
) (sql string, err error)

MySQLJsonUpdate 生成MySQL JSON增量更新SQL语句的快捷方式

func MySQLJsonUpdateWithConfig

func MySQLJsonUpdateWithConfig(
	table string, filed string,
	conditionFiled string, conditionValue interface{},
	data map[string]interface{},
	prefix string, style SeparatorStyle,
) (sql string, err error)

MySQLJsonUpdateWithConfig 生成MySQL JSON增量更新SQL语句

func NewPage

func NewPage(items interface{}, totalNum int64, perPage int, page int) *pageData

NewPage 生成新的分页数据对象

func RenameFile added in v1.2.0

func RenameFile(src, dst string) error

func RenderToFile

func RenderToFile(filename string, input string, data interface{}, isFile bool) (err error)

RenderToFile 渲染模板到文件

func SearchString

func SearchString(slice []string, s string) int

func UnZip

func UnZip(zipFileName, destFileName string) (err error)

解压

func UnderscoreName

func UnderscoreName(name string, upperInitial bool) string

驼峰式写法转为下划线写法

func ValidFilename added in v1.2.0

func ValidFilename(filename string) bool

ValidFilename 有效文件名(Windows标准)

func ValidFilepath added in v1.2.0

func ValidFilepath(filepath string) bool

ValidFilepath 有效文件夹名

func Zip

func Zip(destFileName string, zipFileNames ...string) (err error)

Zip 压缩文件

Types

type BaseStruct

type BaseStruct struct {
	// 编号
	Id int64 `xorm:"pk notnull unique index('idx_id') default(0)" json:"id,string"`
	// 创建时间
	CreatedAt Timestamp `xorm:"created default('2020-02-04 09:55:52')" json:"createdAt"`
	// 最后更新时间
	UpdatedAt Timestamp `xorm:"updated default('2020-02-04 09:55:52')" json:"updatedAt"`
}

BaseStruct Xorm基础模型

func (BaseStruct) Exists added in v1.2.0

func (b BaseStruct) Exists() bool

Exists 对象是否存在

func (BaseStruct) IdString added in v1.2.0

func (b BaseStruct) IdString() string

IdString Id的字符串形式

type BaseTag

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

BaseTag Tag基础

func (*BaseTag) Contains

func (tag *BaseTag) Contains(option string) (contains bool)

Contains 判断Tag是否包含某个属性

type BaseUser

type BaseUser struct {
	BaseStruct `xorm:"extends"`

	// 用户名
	Username DBString `xorm:"varchar(32) notnull default('') unique(uidx_name)" json:"username" validate:"omitempty,min=1,max=32,email"`
	// 手机号
	// 类似于+86-17089792784
	Phone DBString `xorm:"varchar(15) notnull default('') unique(uidx_phone)" json:"phone" validate:"omitempty,mobile"`
	// 密码
	Pwd string `xorm:"varchar(512) notnull default('')" json:"-"`
}

基础用户数据

type CROS added in v1.2.0

type CROS struct {
	AllowOrigins     []string `default:"['*']" yaml:"allowOrigins"`
	AllowCredentials bool     `default:"true" yaml:"allowCredentials"`
}

CROS 跨域配置

type CodeError added in v1.2.0

type CodeError struct {
	// 错误码
	ErrorCode ErrorCode
	// 消息
	Msg string
	// 数据
	Data interface{}
}

CodeError 带错误编号和消息的错误

func NewCodeError added in v1.2.0

func NewCodeError(errorCode ErrorCode, msg string, data interface{}) *CodeError

NewCodeError 创建错误

func (*CodeError) Error added in v1.2.0

func (ce *CodeError) Error() string

func (*CodeError) ToData added in v1.2.0

func (ce *CodeError) ToData() interface{}

func (*CodeError) ToErrorCode added in v1.2.0

func (ce *CodeError) ToErrorCode() ErrorCode

func (*CodeError) ToMsg added in v1.2.0

func (ce *CodeError) ToMsg() string

type CreateStruct added in v1.2.0

type CreateStruct struct {
	// 编号
	Id int64 `xorm:"pk notnull unique index('idx_id') default(0)" json:"id,string"`
	// 创建时间
	CreatedAt Timestamp `xorm:"created default('2020-02-04 09:55:52')" json:"createdAt"`
}

CreateStruct 带创建时间模型

type DBString added in v1.2.0

type DBString string

func (*DBString) FromDB added in v1.2.0

func (s *DBString) FromDB(bytes []byte) error

func (DBString) ToDB added in v1.2.0

func (s DBString) ToDB() ([]byte, error)

type Database added in v1.2.0

type Database struct {
	Type string `default:"sqlite3"`

	Address  string `default:"127.0.0.1:3306"`
	Username string
	Password string
	Protocol string `default:"tcp"`

	Suffix             string
	Prefix             string
	Schema             string `default:"schema"`
	MigrationTableName string `default:"migration"`
	Parameters         string
	Path               string `default:"data.db"`
}

Database 数据库配置

func (*Database) Dsn added in v1.2.0

func (db *Database) Dsn() string

Dsn 取得数据库的DSN

type DeleteStruct added in v1.2.0

type DeleteStruct struct {
	// 编号
	Id int64 `xorm:"pk notnull unique index('idx_id') default(0)" json:"id,string"`
	// 创建时间
	CreatedAt Timestamp `xorm:"created default('2020-02-04 09:55:52')" json:"createdAt"`
	// 最后更新时间
	UpdatedAt Timestamp `xorm:"updated default('2020-02-04 09:55:52')" json:"updatedAt"`
	// 删除时间
	// 用户软删除
	DeletedAt Timestamp `xorm:"deleted default('2020-02-04 09:55:52')" json:"deletedAt"`
}

DeleteStruct 软删除模型

type Duration

type Duration time.Duration

Duration 弥补标准库不能使用ParseDuration

func (*Duration) Duration

func (d *Duration) Duration() time.Duration

Duration 转换成time.Duration

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON 编码成JSON

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON 解析JSON

type Error added in v1.2.0

type Error interface {
	// ToErrorCode 返回错误码
	ToErrorCode() ErrorCode
	// ToMsg 返回错误消息
	ToMsg() string
	// ToData 返回错误实体
	// 在某些错误下,可能需要返回额外的信息给前端处理
	// 比如,认证错误,需要返回哪些字段有错误
	ToData() interface{}
}

Error 接口,符合条件的错误统一处理

type ErrorCode added in v1.2.0

type ErrorCode int

ToErrorCode 错误码

type FileSize added in v1.2.0

type FileSize string

默认大小:B

func (*FileSize) Size added in v1.2.0

func (fs *FileSize) Size() (num int64)

返回多少B

type FileType added in v1.2.0

type FileType int
var (
	FileTypeAny  FileType = 0
	FileTypeDir  FileType = 1
	FileTypeFile FileType = 2
)

type Id

type Id int64

An Id is a custom type used for a snowflake Id. This is used so we can attach methods onto the Id.

func ParseBase2 added in v1.2.0

func ParseBase2(id string) (Id, error)

ParseBase2 converts a Base2 string into a snowflake Id

func ParseBase32 added in v1.2.0

func ParseBase32(b []byte) (Id, error)

ParseBase32 parses a base32 []byte into a snowflake Id NOTE: There are many different base32 implementations so becareful when doing any interoperation.

func ParseBase36 added in v1.2.0

func ParseBase36(id string) (Id, error)

ParseBase36 converts a Base36 string into a snowflake Id

func ParseBase58 added in v1.2.0

func ParseBase58(b []byte) (Id, error)

ParseBase58 parses a base58 []byte into a snowflake Id

func ParseBase64

func ParseBase64(id string) (Id, error)

ParseBase64 converts a base64 string into a snowflake Id

func ParseBytes

func ParseBytes(id []byte) (Id, error)

ParseBytes converts a byte slice into a snowflake Id

func ParseInt64

func ParseInt64(id int64) Id

ParseInt64 converts an int64 into a snowflake Id

func ParseIntBytes

func ParseIntBytes(id [8]byte) Id

ParseIntBytes converts an array of bytes encoded as big endian integer as a snowflake Id

func ParseString

func ParseString(id string) (Id, error)

ParseString converts a string into a snowflake Id

func (Id) Base2 added in v1.2.0

func (f Id) Base2() string

Base2 returns a string base2 of the snowflake Id

func (Id) Base32 added in v1.2.0

func (f Id) Base32() string

Base32 uses the z-base-32 character set but encodes and decodes similar to base58, allowing it to create an even smaller result string. NOTE: There are many different base32 implementations so becareful when doing any interoperation.

func (Id) Base36 added in v1.2.0

func (f Id) Base36() string

Base36 returns a base36 string of the snowflake Id

func (Id) Base58 added in v1.2.0

func (f Id) Base58() string

Base58 returns a base58 string of the snowflake Id

func (Id) Base64

func (f Id) Base64() string

Base64 returns a base64 string of the snowflake Id

func (Id) Bytes

func (f Id) Bytes() []byte

Bytes returns a byte slice of the snowflake Id

func (Id) Int64

func (f Id) Int64() int64

Int64 returns an int64 of the snowflake Id

func (Id) IntBytes

func (f Id) IntBytes() [8]byte

IntBytes returns an array of bytes of the snowflake Id, encoded as a big endian integer.

func (Id) MarshalJSON

func (f Id) MarshalJSON() ([]byte, error)

MarshalJSON returns a json byte array string of the snowflake Id.

func (Id) Node

func (f Id) Node() int64

Snowflake returns an int64 of the snowflake Id node number

func (Id) Step

func (f Id) Step() int64

Step returns an int64 of the snowflake step (or sequence) number

func (Id) String

func (f Id) String() string

String returns a string of the snowflake Id

func (Id) Time

func (f Id) Time() int64

Time returns an int64 unix timestamp in milliseconds of the snowflake Id time

func (*Id) UnmarshalJSON

func (f *Id) UnmarshalJSON(b []byte) error

UnmarshalJSON converts a json byte array of a snowflake Id into an Id type.

type IdStruct

type IdStruct struct {
	// 编号
	Id int64 `xorm:"pk notnull unique index('idx_id') default(0)" json:"id,string"`
}

IdStruct 带序列号的模型

func (IdStruct) IdString

func (b IdStruct) IdString() string

IdString Id的字符串形式

type Int64Slice added in v1.2.0

type Int64Slice []int64

func (*Int64Slice) FromDB added in v1.2.0

func (s *Int64Slice) FromDB(bytes []byte) error

func (Int64Slice) MarshalJSON added in v1.2.0

func (s Int64Slice) MarshalJSON() ([]byte, error)

func (Int64Slice) ToDB added in v1.2.0

func (s Int64Slice) ToDB() ([]byte, error)

func (*Int64Slice) UnmarshalJSON added in v1.2.0

func (s *Int64Slice) UnmarshalJSON(bytes []byte) error

func (*Int64Slice) UnmarshalParam added in v1.2.0

func (s *Int64Slice) UnmarshalParam(src string) error

type JSONSyntaxError

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

A JSONSyntaxError is returned from UnmarshalJSON if an invalid Id is provided.

func (JSONSyntaxError) Error

func (j JSONSyntaxError) Error() string

type NamedTag

type NamedTag struct {
	BaseTag
	// contains filtered or unexported fields
}

NamedTag 描述Golang的Tag标记

func NewNamedTag

func NewNamedTag(tagString string) *NamedTag

NewTag 创建新Tag

func (*NamedTag) GetName

func (tag *NamedTag) GetName() string

GetName 获得Tag的名称

type Paging

type Paging struct {
	// 当前页
	Page int `default:"1" json:"page" validate:"min=1"`
	// 每页个数
	PerPage int `default:"20" json:"perPage" validate:"min=1"`
	// 查询关键字
	Keyword string `json:"keyword"`
	// 排序顺序
	SortOrder string `default:"DESC" json:"sortOrder" validate:"oneof=asc ASC ascending ASCENDING desc DESC descending DESCENDING"`
}

Paging 分页对象

func (*Paging) Limit

func (p *Paging) Limit() int

Limit 获得限制个数

func (*Paging) MySQL

func (p *Paging) MySQL() (start int, offset int)

MySQL 获得MySQL需要的分页参数

func (*Paging) OrderBy

func (p *Paging) OrderBy(sorter Sorter) string

排序字符串

func (*Paging) Start

func (p *Paging) Start() int

Start 获得开始下标

type SeparatorStyle

type SeparatorStyle struct {
	Before string // Prepend to key
	Middle string // Add between keys
	After  string // Append to key
}

The style of keys. If there is an input with two nested keys "f" and "g", with "f" at the root,

{ "f": { "g": ... } }

the output will be the concatenation

f{Middle}{Before}g{After}...

Any struct element may be blank. If you use Middle, you will probably leave Before & After blank, and vice-versa. See examples in flatten_test.go and the "Default styles" here.

type Snowflake

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

A Snowflake struct holds the basic information needed for a snowflake generator node

func NewSnowflake

func NewSnowflake(node int64) (*Snowflake, error)

NewSnowflake returns a new snowflake node that can be used to generate snowflake IDs

func (*Snowflake) Next

func (s *Snowflake) Next() Id

Next creates and returns a unique snowflake Id To help guarantee uniqueness - Make sure your system is keeping accurate system time - Make sure you never have multiple nodes running with the same node Id

func (*Snowflake) NextId

func (s *Snowflake) NextId() int64

NextId 下一个长整形Id

func (*Snowflake) NextString

func (s *Snowflake) NextString() string

NextString 下一个字符串形式的Id

type Sorter

type Sorter interface {
	SortFieldName() string
}

Sorter 排序

type StringBuilder added in v1.2.0

type StringBuilder struct {
	*bytes.Buffer
}

内嵌bytes.StringBuilder,支持连写

func NewStringBuilder added in v1.2.0

func NewStringBuilder() *StringBuilder

func (*StringBuilder) Append added in v1.2.0

func (b *StringBuilder) Append(i interface{}) *StringBuilder

type StringSlice

type StringSlice []string

func (*StringSlice) UnmarshalParam

func (ss *StringSlice) UnmarshalParam(src string) error

type Tagger

type Tagger interface {
	Contains(option string) (contains bool)
}

Tagger 支持Tag的接口

type Timestamp

type Timestamp time.Time

Timestamp 时间戳

func ParseTimestamp

func ParseTimestamp(time time.Time) Timestamp

ParseTimestamp 从Time对象生成Timestamp

func (Timestamp) IsZero

func (t Timestamp) IsZero() bool

IsZero 是否是零值

func (Timestamp) MarshalJSON

func (t Timestamp) MarshalJSON() ([]byte, error)

MarshalJSON 序列化成JSON时调用

func (Timestamp) Time

func (t Timestamp) Time() time.Time

Time 取得真实的Time对象

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(b []byte) error

UnmarshalJSON 反序列化成JSON时调用

func (*Timestamp) UnmarshalParam

func (t *Timestamp) UnmarshalParam(src string) error

UnmarshalParam 从Echo参数转换

type UpdateStruct added in v1.2.0

type UpdateStruct struct {
	// 编号
	Id int64 `xorm:"pk notnull unique index('idx_id') default(0)" json:"id,string"`
	// 最后更新时间
	UpdatedAt Timestamp `xorm:"updated default('2020-02-04 09:55:52')" json:"updatedAt"`
}

UpdateStruct 带修改时间模型

Jump to

Keyboard shortcuts

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