easyutils

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2019 License: MIT Imports: 31 Imported by: 4

README

easyutils

easyutils Golang 常用工具库

.
├── LICENSE
├── README.md
├── base64Captcha.go 验证码
├── crypto.go 加密解密相关
├── file.go 文件相关
├── go.mod
├── go.sum
├── miscellaneous.go 杂项
├── new_session.go session相关 新(开发中)
├── reptile.go 爬虫相关
├── session.go session相关 旧
├── simpleTime.go 时间相关
├── test 测试
│   └── tootl_test.go
├── token.go token相关
├── concurrent 并发控制
├── clog 日志工具
└── uuid.go uuid相关

把生活和工作当中常用的东西抽离出来 严格单元测试 保证代码质量

简单用法

获取
go get github.com/dollarkillerx/easyutils
crypto加密包
  • 把str转为md5
    md5str := Md5Encode(string)
    
  • sha1
    sha1str := Sha1Encode("hello")
    
  • SHA256
    Sha256Encode(str string) string
    
  • RSA256 公钥密钥对生成
    e, priKey, pubKey := GenRsaKey(1024) // 1024 密钥长度
    
  • Rsa256 加密
    RsaEncrypt(origData,pubKey []byte) ([]byte,error)
    
  • Rsa256 加密简单
    RsaEncryptSimple(origData,pubKey string) (string,error)
    
  • Rsa256 解密
    RsaDecrypt(ciphertext,privateKey []byte) ([]byte, error)
    
  • Rsa256 解密简单
    RsaDecryptSimple(ciphertext,privateKey string) (string, error)
    
  • Rsa256 签名
    RsaSignVer(data,signature,publicKey []byte) error
    
  • Rsa256 简单签名
    RsaSignSimple(data, prvKey string) (string, error)
    
  • Rsa256 验签
    RsaSignVer(data,signature,publicKey []byte) error
    
  • Rsa256 简单验签
    RsaSignVerSimple(data,signature,publicKey string) error
    
  • Base64标准编码
    Base64Encode(data []byte) string
    
  • Base64标准解码
    Base64Decode(s string) ([]byte,error)
    
  • Base64URL编码
    Base64URLEncode(data []byte) string
    
  • Base64URL解码
    Base64URLDecode(s string) ([]byte,error)
    
simpleTime 时间包
  • 获取当前时间戳,时区默认亚洲上海
    timeString := TimeGetNowTimeStr()
    
  • 时间戳转换为日期
    日期,err := TimeGetTimeToString(时间戳string)
    
  • 日期转换为时间戳
    时间戳str,err := TimeGetStringToTime(日期)
    
uuid包
  • 获取uuid
    uuidstr,err := NewUUID()
    
  • 获取当前uuid不带-
    uuidstr,err := NewUUIDSimplicity()
    
  • 超级随机
    SuperRand() string
    
session 包
  • 获取session
    session := SessionGenerate("dollarkiller",6*60*60)
    
  • 获得session数据
    node, e := SessionGetData(session)
    
  • 验证session
    bool := SessionCheck(session)
    
  • 销毁session
    SessionDel(session)
    
file包
  • 判断文件夹是否存在
    ok,err := PathExists("./file")
    
  • 如果文件夹不存在就会创建文件夹
    err := DirPing("./file")
    
  • 获取文件后缀
    str,err := FileGetPostfix("123.text")
    
  • 获得随机文件名 传入postfilx后缀
    filename := FileGetRandomName(postfilx string)
    
  • 获取文件sha1
    str := FileGetSha1(file *os.File)
    
  • 获取文件MD5
    str := FileGetMD5(file *os.File)
    
  • 保存文件 并从命名 Simple 版本
    FileSaveRenameSimple(name string, data []byte, path string) (string, error)
    
  • 保存文件 Simple版本
    FileSaveSimple(name string, data []byte, path string) error 
    
Token
  • 初始化
    _, priKey, pubKey := GenRsaKey(1024)
        jwt := NewUtilsToken(priKey, pubKey)
    
  • 生成JWT
    s, e := jwt.GeneraJwtToken(head, payload)
    
  • 生成JWT 缓存版本
    s, e := jwt.GeneraJwtTokenToData(head, payload)
    
  • 验证JWT
    bool := jwt.VerificationToken(s)
    
  • 验证JWT 缓存版本
    bool := jwt.VerificationTokenByData(s)
    
EasyToken
  • 生成token
    EasyJwtGeneraToken(data *EasyJwtPayload,hour int) (string,error)
    
  • 验证签名
    EasyJwtVerification(jwt string) error
    
  • 验证用户是否已经登录
    EasyJwtCheckUserLogin(email string) (token string,err error)
    
验证码 是对base64Captcha包装
  • 获取数字验证码
    CaptchaNum() (captchaId, base64Png string)
    
  • 获取算数验证码
    CaptchaMath() (captchaId, base64Png string)
    
  • 获取音频验证码
    CaptchaMP3() (captchaId, base64MP3 string)
    
  • 验证
    CaptchaCheck(captchaId, verifyValue string) (int, error)
    
杂项
  • 获取区间随机数
    Random(min,max int) int
    
  • 计算offset
    OffsetMath(page,limit int) int 
    
  • UrlEncoding
    UrlEncoding(urls string) (string,error)
    
LayUi 兼容
  • 分页
    • 分页包装数据
      LayPage(count int,data interface{}) *LayUiPage
      
    • 接受用户传入结构体
    • 发送结构体
    • 默认定义 空数据 雨 数据异常发送模板
简单爬虫tools
  • 初始化
    // url,username,password
    rep,err := InitProxy(arg ...string) (*ProxySt, error)
    
  • 获取随机UserAgent (假装自己是普通用户)
    rep.ReptileGetUserAgent() string
    
  • 获取搜索引擎UserAgent (假装自己是搜索引擎)
    rep.ReptileGetSpiderAgent() string
    
  • 发送请求 (假装自己是搜索引擎)
    rep.ReptileSpiderRequestFrom(targerUrl string, body io.Reader, cookies []*http.Cookie) (*http.Response, error)
    
  • 发送请求 (假装自己是普通用户)
    rep.ReptileUserRequestFrom(targerUrl string, body io.Reader, cookies []*http.Cookie) (*http.Response, error)
    
  • 文件下载
    rep.ReptileDownloadSimple(targerUrl string, cookies []*http.Cookie) ([]byte, error)
    
  • 文件下载并保存
    rep.ReptileDownloadAndSaveSimple(targerUrl string, cookies []*http.Cookie, name, path string) (string, error)
    
  • 验证代理是否可用
    rep.CheckProxy() error
    
httplib 基于beego
  • 假装用户去请求
    EuUserGet(url string) ([]byte,error)
    
  • 假装搜索引擎去请求
    EuSpiderGet(url string,) ([]byte,error)
    
  • post请求
    req := httplib.Post("https://google.com/")
    req.Param("username","google")
    req.Param("password","123456")
    
  • 设置head
    req := httplib.Post("https://google.com/")
    req.Header("Accept-Encoding","gzip,deflate,sdch")
    
clog
  • 带方法地址的打印
    clog.Println("2312")
    
  • Sprint
    clog.Sprint(string) string
    
concurrent 并发包
  • 对象池
    • 创建对象池
      NewObjPoll(obj interface{},num int) *ObjPoll
      
    • 获取对象
      (p *ObjPoll) GetObj(timeout time.Duration) (interface{},error)
      
    • 放回对象
      (p *ObjPoll) Release(obj interface{}) error
      
压缩相关
  • Zip
    • 压缩
    err := compression.Zip("./captcha_test", "out.zip")
    
    • 解压
    err := compression.Unzip("out.zip", "./ps")
    
通知邮件 (公用邮件服务器)
gemail.SendNifoLog([]string{toUser},fromUser,subject)
form 绑定
  • 自动绑定
    Band(req *http.Request, obj interface{}) error
    
  • 绑定Json
    BindJson(req *http.Request, obj interface{}) error
    
  • 绑定Form
    BindForm(req *http.Request, obj interface{}) error
    
简单解析Json数据不用写Struct
func TestMap(t *testing.T) {
	data := `
	{
		"device": "this is device",
		"ppc": {
			"ok":"ppc"
		},	
		"data": [
			{
				"humidity": "this is humidity",
				"time": "this is time"
			},
			"hello"
		]
	}
	`

	mapun, e := gmap.Unmarshal(data)
	if e != nil {
		panic(e)
	}

	// 获取string
	s, b := mapun.GetString("device")
	if b {
		log.Println(s)
	}

	// 获取map
	i3, i4 := mapun.GetMap("ppc")
	if i4 {
		log.Println(i3)
	}

	// 获取slice
	getMap, i := mapun.GetSlice("data")
	if i {
		log.Println(getMap)
	}

	//i2,bo := mapun.GetMap2(getMap[0])
	//if bo {
	//	log.Println(i2)
	//}

	// 获取 slice map
	sliceMap, i5 := mapun.GetSliceMap("data")
	if i5 {
		log.Println(sliceMap)
	}
}

Documentation

Overview

* * Created by GoLand * User: dollarkiller * Date: 19-6-12 * Time: 上午11:53 *

*

* * Created by GoLand * User: dollarkiller * Date: 19-7-11 * Time: 上午11:08 *

* * Created by GoLand * User: dollarkiller * Date: 19-7-9 * Time: 下午6:10 *

* * Created by GoLand * User: dollarkiller * Date: 19-6-9 * Time: 下午12:08 * @Description: 自研 多兼容 session (设计思路一个中央控制器 一个interface实现控制器下的方法) * @Github: https://github.com/dollarkillerx *

* * Created by GoLand * User: dollarkiller * Date: 19-7-3 * Time: 下午8:47 *

Index

Constants

This section is empty.

Variables

View Source
var (
	LayEmptyData = &LayUiPage{Code: 0, Count: 0, Msg: "Empty Data"}  // 空数据
	LayErrorData = &LayUiPage{Code: -1, Count: 0, Msg: "Error Data"} // 异常数据
)

定义空数据 当无数据 或者数据异常时返回

Functions

func AESDecrypt added in v1.0.4

func AESDecrypt(key []byte, ciphertext []byte) ([]byte, bool)

Decrypt from base64 to decrypted string

func AESEncrypt added in v1.0.4

func AESEncrypt(key []byte, plaintext []byte) ([]byte, bool)

对称加密 AES 高级标准加密 Encrypt string to base64 crypto using AES

func Base64Decode

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

Base64解码

func Base64Encode

func Base64Encode(data []byte) string

Base64编码

func Base64URLDecode

func Base64URLDecode(s string) ([]byte, error)

Base64URL解码

func Base64URLEncode

func Base64URLEncode(data []byte) string

Base64URL编码

func DirPing

func DirPing(path string) error

如果文件夹不存在就会创建

func EasyJwtCheckUserLogin

func EasyJwtCheckUserLogin(email string) (token string, err error)

验证用户是否已经登录

func EasyJwtGeneraToken

func EasyJwtGeneraToken(data *EasyJwtPayload, hour int) (string, error)

生成token 载荷

func EasyJwtVerification

func EasyJwtVerification(jwt string) error

验证签名 jwt

func FielGetSize

func FielGetSize(filename string) int64

获取文件大小

func FileGetMD5

func FileGetMD5(file *os.File) string

获取文件MD5

func FileGetPostfix

func FileGetPostfix(filename string) (string, error)

获取文件后缀

func FileGetRandomName

func FileGetRandomName(postfilx string) string

获得随机文件名 传入postfilx后缀 几乎不会重复

func FileGetSha1

func FileGetSha1(file *os.File) string

获得文件sha1

func FileSaveRenameSimple

func FileSaveRenameSimple(name string, data []byte, path string) (string, error)

保存文件 并从命名 Simple 版本 return: NewName,error

func FileSaveSimple

func FileSaveSimple(name string, data []byte, path string) error

保存文件 return error

func GenRsaKey

func GenRsaKey(bits int) (e error, priKey string, pubKey string)

RSA256 公钥密钥对生成 @params: bits 密钥长度 @returns: private 密钥 @returns: public 公钥

func GetFullChinaName

func GetFullChinaName() string

获取随机中文名

func Md5Encode

func Md5Encode(str string) string

获取md5

func NewUUID

func NewUUID() (string, error)

func NewUUIDSimplicity

func NewUUIDSimplicity() (string, error)

获取没有 - 的uuid

func OffsetMath

func OffsetMath(page, limit int) int

计算分页offset

func PathExists

func PathExists(path string) (bool, error)

判断文件夹是否存在

func Prepend

func Prepend(sc *[]interface{}, value interface{}) *[]interface{}

数组

func Random

func Random(min, max int) int

获取区间内随机数

func ReptileGetSpiderAgent

func ReptileGetSpiderAgent() string

获取蜘蛛agent

func ReptileGetUserAgent

func ReptileGetUserAgent() string

获取随机UserAgent

func RsaDecrypt

func RsaDecrypt(ciphertext, privateKey []byte) ([]byte, error)

Rsa256 解密 @params: ciphertext 加密数据 @Params: prvKey 私钥

func RsaDecryptSimple

func RsaDecryptSimple(ciphertext, privateKey string) (string, error)

Rsa256 解密简单

func RsaEncrypt

func RsaEncrypt(origData, pubKey []byte) ([]byte, error)

Rsa256 加密 @params: origData 原始数据 @Params: pubKey 公钥

func RsaEncryptSimple

func RsaEncryptSimple(origData, pubKey string) (string, error)

Rsa256 加密简单 @params: origData 原始数据 @Params: pubKey 公钥

func RsaSign

func RsaSign(data, prvKey []byte) ([]byte, error)

Rsa256 签名 @params: origData 需要签名的数据 @Params: prvKey 私钥

func RsaSignSimple

func RsaSignSimple(data, prvKey string) (string, error)

Rsa256 签名简单 @params: origData 需要签名的数据 @Params: prvKey 私钥

func RsaSignVer

func RsaSignVer(data, signature, publicKey []byte) error

Rsa256 验签 @params: data 原始数据 @params: signature 签名 @params: publicKey 公钥

func RsaSignVerSimple

func RsaSignVerSimple(data, signature, publicKey string) error

Rsa256 验签简单 @params: data 原始数据 @params: signature 签名 @params: publicKey 公钥

func Sha1Encode

func Sha1Encode(str string) string

获取sha1

func Sha256Encode

func Sha256Encode(str string) string

获取sha256

func SliceDel

func SliceDel(sc *[]interface{}, index int) *[]interface{}

数组删除

func SuperRand

func SuperRand() string

func TimeGetNowTime

func TimeGetNowTime() int

获取当前时间

func TimeGetNowTimeStr

func TimeGetNowTimeStr() string

获取当前时间

func TimeGetStringToTime

func TimeGetStringToTime(times string) (string, error)

日期str转时间戳

func TimeGetTimeToString

func TimeGetTimeToString(times string) (string, error)

时间戳转日期str

func TrimHtml

func TrimHtml(src string) string

过滤html元素

func UrlEncoding

func UrlEncoding(urls string) (string, error)

url encoding

Types

type EasyJwtPayload

type EasyJwtPayload struct {
	Iss  string      `json:"iss"` // 签发人
	Exp  int         `json:"exp"` // 过期时间
	Msg  string      `json:"msg"` // 用户自义定数据
	Data interface{} `json:"data"`
}

type GoSessionNode

type GoSessionNode struct {
}

================================不同数据源的实现===================================== 系统自带 gocache 存储

func (*GoSessionNode) Del

func (g *GoSessionNode) Del(id string) error

func (*GoSessionNode) Expired

func (g *GoSessionNode) Expired(id string) bool

func (*GoSessionNode) Get

func (g *GoSessionNode) Get(id string) (*Session, error)

func (*GoSessionNode) Set

func (g *GoSessionNode) Set(data *Session) (string, error)

func (*GoSessionNode) SetTime

func (g *GoSessionNode) SetTime(data *Session, tim time.Duration) (string, error)

type JwtHeader

type JwtHeader struct {
	Alg  string `json:"alg"`  // 算法名称
	Type string `json:"type"` // 类型
}

type JwtPayload

type JwtPayload struct {
	Iss string `json:"iss"` // 签发人
	Exp string `json:"exp"` // 过期时间
	Sub string `json:"sub"` // 主题
	Nbf string `json:"nbf"` // 生效时间
	Iat string `json:"iat"` // 签发时间
	Jti string `json:"jti"` // 编号
}

type JwtUtils

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

token

func NewUtilsToken

func NewUtilsToken(prikey string, pubkey string) *JwtUtils

初始化token

func (*JwtUtils) GeneraJwtToken

func (t *JwtUtils) GeneraJwtToken(header *JwtHeader, payload *JwtPayload) (string, error)

生成JWT

func (*JwtUtils) GeneraJwtTokenToData

func (t *JwtUtils) GeneraJwtTokenToData(header *JwtHeader, payload *JwtPayload) (string, error)

生成token并存入 内存中

func (*JwtUtils) VerificationToken

func (t *JwtUtils) VerificationToken(jwt string) bool

验证token

func (*JwtUtils) VerificationTokenByData

func (t *JwtUtils) VerificationTokenByData(jwt string) bool

验证token从缓存中

type LayGet

type LayGet struct {
	Page  int `form:"page"`
	Limit int `form:"limit"`
}

分页客户端请求结构体

type LayUiPage

type LayUiPage struct {
	Code  int         `json:"code"`
	Count int         `json:"count"`
	Data  interface{} `json:"data"`
	Msg   string      `json:"msg"`
}

分页返回数据结构体

func LayPage

func LayPage(count int, data interface{}) *LayUiPage

包装分页数据

type ProxySt

type ProxySt struct {
	UserName    string
	Password    string
	ProxyServer string
	// contains filtered or unexported fields
}

func InitProxy

func InitProxy(arg ...string) (*ProxySt, error)

初始化代理 url,username,password

func (*ProxySt) CheckProxy

func (p *ProxySt) CheckProxy() error

验证代理是否可用

func (*ProxySt) ReptileDownloadAndSaveSimple

func (p *ProxySt) ReptileDownloadAndSaveSimple(targerUrl string, cookies []*http.Cookie, name, path string) (string, error)

文件下载并保存 目标地址,cookies,文件名称,新路径

func (*ProxySt) ReptileDownloadSimple

func (p *ProxySt) ReptileDownloadSimple(targerUrl string, cookies []*http.Cookie) ([]byte, error)

文件下载

func (*ProxySt) ReptileSpiderRequestFrom

func (p *ProxySt) ReptileSpiderRequestFrom(targerUrl string, body io.Reader, cookies []*http.Cookie) (*http.Response, error)

请求 假装成 蜘蛛

func (*ProxySt) ReptileUserRequestFrom

func (p *ProxySt) ReptileUserRequestFrom(targerUrl string, body io.Reader, cookies []*http.Cookie) (*http.Response, error)

请求 假装成 用户

type Session

type Session struct {
	Name           string
	Identification string                 // 唯一身份标识
	Data           map[string]interface{} // 存储器
	CreationTime   int64                  // 创建时间
	ExpirationTime int64                  // 过期时间
}

session node

type SessionInterface

type SessionInterface interface {
	Get(id string) (*Session, error)                          // 拥有通过id获取session
	Set(data *Session) (string, error)                        // 返回id and 错误信息
	SetTime(data *Session, tim time.Duration) (string, error) // 返回id and 错误信息
	Del(id string) error
	Expired(id string) bool // 检测是否过期  过期返回false 反之true
}

func SessionGetByGoCache

func SessionGetByGoCache() SessionInterface

Directories

Path Synopsis
* * @Author: DollarKiller * @Description: 压缩字符串 * @Github: https://github.com/dollarkillerx * @Date: Create in 20:38 2019-09-25 * * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 16:25 2019-09-21
* * @Author: DollarKiller * @Description: 压缩字符串 * @Github: https://github.com/dollarkillerx * @Date: Create in 20:38 2019-09-25 * * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 16:25 2019-09-21
* * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 16:27 2019-09-21
* * @Author: DollarKiller * @Description: * @Github: https://github.com/dollarkillerx * @Date: Create in 16:27 2019-09-21
* * @Author: DollarKiller * @Description: form 结构体绑定 * @Github: https://github.com/dollarkillerx * @Date: Create in 17:41 2019-09-14
* * @Author: DollarKiller * @Description: form 结构体绑定 * @Github: https://github.com/dollarkillerx * @Date: Create in 17:41 2019-09-14
* * @Author: DollarKiller * @Description: 添加方法 * @Github: https://github.com/dollarkillerx * @Date: Create in 11:26 2019-09-15
* * @Author: DollarKiller * @Description: 添加方法 * @Github: https://github.com/dollarkillerx * @Date: Create in 11:26 2019-09-15
* * @Author: DollarKiller * @Description: 邮件相关 * @Github: https://github.com/dollarkillerx * @Date: Create in 14:45 2019-09-12
* * @Author: DollarKiller * @Description: 邮件相关 * @Github: https://github.com/dollarkillerx * @Date: Create in 14:45 2019-09-12
* * @Author: DollarKiller * @Description: gmap json to map * @Github: https://github.com/dollarkillerx * @Date: Create in 13:51 2019-10-08
* * @Author: DollarKiller * @Description: gmap json to map * @Github: https://github.com/dollarkillerx * @Date: Create in 13:51 2019-10-08
* * @Author: DollarKiller * @Description: 尽最大可能获取用户ip * @Github: https://github.com/dollarkillerx * @Date: Create in 17:01 2019-09-18
* * @Author: DollarKiller * @Description: 尽最大可能获取用户ip * @Github: https://github.com/dollarkillerx * @Date: Create in 17:01 2019-09-18
Package uuid provides implementation of Universally Unique Identifier (UUID).
Package uuid provides implementation of Universally Unique Identifier (UUID).

Jump to

Keyboard shortcuts

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