kerbalwzygo

package module
v0.0.0-...-3d73107 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2020 License: MPL-2.0 Imports: 22 Imported by: 0

README

kerbalwzygo

个人使用Golang进行后端开发时封装的一些工具对象

这里封装都是写工具的初级原型, 具体融合到项目中时可能需要做一些修改

懒得封装到兼容性很高, 我个人认为纯粹调包开发非常无聊而且包内有些功能也用不上, 抽空自己造一造轮子其实挺有意思的


  • m_cache_in_redis
    • 缓存中间件, 提供加载, 存储, 清理缓存的功能函数, 具体函数功能请看注释(PS: 所有代码的注释都是英文写的, 懒得在写代码的时候切换输入法😂)
  • m_cors
    • 跨域中间件, 解决前后端分离项目的跨域问题, 本质上修改响应头, 添加跨域相关的控制Headers信息
  • m_flow_limit
    • 限流中间件, 利用标准库中的Token Bucket算法函数, 控制单位时间内处理的请求数量, 实现限流效果

  • u_gin_style_logger
    • 日志输出对象, 帮助我们输出格式和Gin框架默认日志格式一样的日志信息(PS: 个人认为在不考虑使用日志信息做数据分析的情况下, Gin框架本身的日志格式挺好看的, zap或者logrus都很好用! 就是配置起来参数太多了)
  • u_rotate_file_writer
    • 循环文件写入器, 可以帮助我们自己实现循环文件日志
  • u_string
    • 字符串和Byte数组常用的一些操作的函数, 详情看代码和注释
  • u_time
    • 日期, 时间, 时间戳常用的一些操作函数, 详情看代码和注释
  • u_jwt_token
    • JWT Token字符串的生成, 解析, 刷新等函数

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	TokenExpired     = errors.New(" Token is expired")
	TokenNotValidYet = errors.New(" Token not active yet")
	TokenMalformed   = errors.New(" That's not even a token")
	TokenInvalid     = errors.New(" Couldn't handle this token:")
)

Error notes

View Source
var ErrIndexOutOfRange = errors.New("the 'start' or 'end' index value is out of range")
View Source
var ErrStartLargeThenEnd = errors.New("the 'start' index value is over then 'end'")
View Source
var ErrTokenNumber = errors.New("secToken的值必须小于等于maxToken的值")
View Source
var ErrTooManyRequests = errors.New(http.StatusText(429))

Functions

func BytesMD5Hash

func BytesMD5Hash(data []byte) string

Get the MD5 hash value of bytes

func CORSMiddleware

func CORSMiddleware(origin string) gin.HandlerFunc

跨域处理中间

func CacheInRedisMiddleware

func CacheInRedisMiddleware(cacheUrlTags []string) gin.HandlerFunc

缓存读取中间件

func CleanCacheInRedis

func CleanCacheInRedis(tag string) error

删除缓存

func CreateJWTToken

func CreateJWTToken(claims CustomJWTClaims, salt []byte) (string, error)

生成JWT TOKEN: claims 载体数据, salt加密盐值

func DatetimeStr2Timestamp

func DatetimeStr2Timestamp(datetime string) (int64, error)

Parse a datetime string into unix timestamp, unit:sec

func FlowLimitMiddleware

func FlowLimitMiddleware(secToken rate.Limit, maxToken int) gin.HandlerFunc

限流中间件 每秒产生secToken个令牌, 最多存放maxToken个令牌, 即一秒内最多允许maxToken个请求

func InitRedisClient

func InitRedisClient(addr, password string, db int)

初始化RedisClient, 在程序启动阶段的代码中去执行

func LoadCacheInRedis

func LoadCacheInRedis(c *gin.Context) ([]byte, error)

加载缓存

func MultiStringMD5Hash

func MultiStringMD5Hash(data ...string) string

Get the MD5 hash value of multi string

func NowDatetimeStr

func NowDatetimeStr() string

Get the datetime string of now

func NowTimestamp

func NowTimestamp() int64

Get the timestamp of now, unit: sec

func RefreshJWTToken

func RefreshJWTToken(tokenStr string, salt []byte, survivalTime time.Duration) (string, error)

刷新JWT TOKEN tokenStr TOKEN字符串, salt加密盐值, survivalTime存活时间

func SafeSliceString

func SafeSliceString(data string, start, end int) (string, error)

安全的切割字符串: data原字符串, start切片起点, end切片终点+1 Direct cutting of string may cause character scrambling, because some character could be 3 or 4 byte. Translate the 'string' into 'rune' before cutting could make safe

func SetCORSHeaders

func SetCORSHeaders(header http.Header, allowOrigin string)

func StorageCacheInRedis

func StorageCacheInRedis(c *gin.Context, body gin.H, expire time.Duration) ([]byte, error)

存储缓存数据

func StringContainsHan

func StringContainsHan(data string) bool

检查字符串是否包含中文字符

func StringContainsSpace

func StringContainsSpace(data string) bool

检查字符串是否包含空白字符

func StringMD5Hash

func StringMD5Hash(data string) string

Get the MD5 hash value of string

func Timestamp2DatetimeStr

func Timestamp2DatetimeStr(timestamp int64) string

Get the datetime string of one timestamp

func TodayDateStr

func TodayDateStr() string

Get the date string of today

Types

type CustomJWTClaims

type CustomJWTClaims struct {
	CustomData interface{} `json:"custom_data"`
	jwt.StandardClaims
}

自定义载体, CustomData用于保存自定义的数据; jwt.StandardClaims用于存储载体附属信息, 特别是过期时间

func ParseJWTToken

func ParseJWTToken(tokenStr string, salt []byte) (*CustomJWTClaims, error)

解析JWT TOKEN: tokenStr TOKEN字符串, salt加密盐值

type GinStyleLogger

type GinStyleLogger struct {
	// Optional. Default value is gin.defaultGinStyleLogFormatter
	Formatter gin.LogFormatter

	// Output is a writer where logs are written.
	// Optional. Default value is gin.DefaultWriter.
	Output io.Writer
}

Logger for output the custom log information with gin style in the gin.HandlerFunc.

func NewGinStyleLogger

func NewGinStyleLogger(out io.Writer, formatter gin.LogFormatter) *GinStyleLogger

return a StyleLogger instance with the params. when the param is nil, will use the default value.

func (*GinStyleLogger) Fprintln

func (p *GinStyleLogger) Fprintln(c *gin.Context, statusCode int, message string)

Output the log information with custom status code and message.

type RotateFileWriter

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

Custom rotate file writer.

func NewRotateFileWriter

func NewRotateFileWriter(fileName, dirPath string, maxCount int, maxSize int64) *RotateFileWriter

循环文件写入器: fileName基本文件名, dirPath文件夹路径, maxCount最大文件数量, maxSize最大文件体积

func (*RotateFileWriter) Init

func (obj *RotateFileWriter) Init()

Initial method, check whether the log dir existed and have history log files

func (*RotateFileWriter) Write

func (obj *RotateFileWriter) Write(p []byte) (n int, err error)

Jump to

Keyboard shortcuts

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