master
李光春 3 years ago
parent eb5d188c64
commit 212f0a0415

@ -1,57 +0,0 @@
package aes
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
)
// Encrypt 加密 aes_128_cbc
func Encrypt(encryptStr string, key []byte, iv string) (string, error) {
encryptBytes := []byte(encryptStr)
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
blockSize := block.BlockSize()
encryptBytes = pkcs5Padding(encryptBytes, blockSize)
blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
encrypted := make([]byte, len(encryptBytes))
blockMode.CryptBlocks(encrypted, encryptBytes)
return base64.URLEncoding.EncodeToString(encrypted), nil
}
// Decrypt 解密
func Decrypt(decryptStr string, key []byte, iv string) (string, error) {
decryptBytes, err := base64.URLEncoding.DecodeString(decryptStr)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
blockMode := cipher.NewCBCDecrypter(block, []byte(iv))
decrypted := make([]byte, len(decryptBytes))
blockMode.CryptBlocks(decrypted, decryptBytes)
decrypted = pkcs5UnPadding(decrypted)
return string(decrypted), nil
}
func pkcs5Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
func pkcs5UnPadding(decrypted []byte) []byte {
length := len(decrypted)
unPadding := int(decrypted[length-1])
return decrypted[:(length - unPadding)]
}

@ -1,3 +1,3 @@
module gopkg.in/dtapps/go-library.v2/daes
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,11 @@
package ddecimal
import (
v20210726 "github.com/dtapps/go-library/daes/v20210726"
"log"
"testing"
)
func TestName(t *testing.T) {
log.Println(v20210726.Decimal(2.3333))
}

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/ddecimal
go 1.16

@ -1,4 +1,4 @@
package decimal
package v20210726
import (
"fmt"

@ -1,10 +0,0 @@
package decimal
import (
"log"
"testing"
)
func TestName(t *testing.T) {
log.Println(Decimal(2.3333))
}

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/dingtalk
go 1.16

@ -1,69 +0,0 @@
package message
type Message struct {
MsgType MsgType_ `json:"msgtype"`
Text Text_ `json:"text"`
Link Link_ `json:"link"`
Markdown Markdown_ `json:"markdown"`
ActionCard ActionCard_ `json:"actionCard"`
FeedCard FeedCard_ `json:"feedCard"`
}
type MsgType_ string
const (
TextStr MsgType_ = "text"
LinkStr MsgType_ = "link"
MarkdownStr MsgType_ = "markdown"
ActionCardStr MsgType_ = "actionCard"
FeedCardStr MsgType_ = "feedCard"
)
// Text_ text类型
type Text_ struct {
Content string `json:"content"`
At At_ `json:"at"`
}
// At_ At类型
type At_ struct {
AtMobiles []string `json:"atMobiles"`
IsAtAll bool `json:"isAtAll"`
}
// Link_ link类型
type Link_ struct {
Text string `json:"text"`
Title string `json:"title"`
PicUrl string `json:"picUrl"`
MessageUrl string `json:"messageUrl"`
}
// Markdown_ markdown类型
type Markdown_ struct {
Title string `json:"title"`
Text string `json:"text"`
At At_ `json:"at"`
}
// ActionCard_ 整体跳转actionCard
type ActionCard_ struct {
Title string `json:"title"`
Text string `json:"text"`
BtnOrientation string `json:"btnOrientation"`
SingleTitle string `json:"singleTitle"`
SingleURL string `json:"singleUrl"`
HideAvatar string `json:"hideAvatar"`
BtnS []Btn_ `json:"btns"`
}
// Btn_ Btn类型
type Btn_ struct {
Title string `json:"title"`
ActionURL string `json:"actionURL"`
}
// FeedCard_ FeedCard类型
type FeedCard_ struct {
Links []Link_ `json:"links"`
}

@ -1,4 +1,4 @@
package dingtalk
package v20210726
import (
"crypto/hmac"
@ -6,15 +6,22 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"gopkg.in/dtapps/go-library.v2/dingtalk/message"
params "github.com/dtapps/go-library/params/v20210726"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
const api = "https://oapi.dingtalk.com/robot/send"
// Parameter 参数
type Parameter map[string]interface{}
// ParameterEncode 参数
type ParameterEncode []string
type DingBot struct {
Secret string
AccessToken string
@ -25,16 +32,12 @@ type response struct {
Errmsg string `json:"errmsg"`
}
func (bot *DingBot) Send(msg message.Message) (response, error) {
func (bot *DingBot) Send(param Parameter) (response, error) {
timestamp := time.Now().UnixNano() / 1e6
var response response
signStr := sign(timestamp, bot.Secret)
dingUrl := fmt.Sprintf("%s?access_token=%s&timestamp=%d&sign=%s", api, bot.AccessToken, timestamp, signStr)
j, e := json.Marshal(msg)
if e != nil {
return response, e
}
resp, e := http.Post(dingUrl, "application/json", strings.NewReader(string(j)))
resp, e := http.Post(dingUrl, "application/json", strings.NewReader(param.getRequestData()))
if e != nil {
return response, e
}
@ -55,3 +58,14 @@ func sign(t int64, secret string) string {
result := hmac256.Sum(nil)
return base64.StdEncoding.EncodeToString(result)
}
// 获取请求数据
func (p Parameter) getRequestData() string {
// 公共参数
args := url.Values{}
// 请求参数
for key, val := range p {
args.Set(key, params.GetParamsString(val))
}
return args.Encode()
}

@ -1,4 +1,4 @@
module gopkg.in/dtapps/go-library.v2/dredis
module github.com/dtapps/go-library/dredis
go 1.16

@ -1,4 +1,4 @@
module gopkg.in/dtapps/go-library.v2/dssh
module github.com/dtapps/go-library/dssh
go 1.16

@ -1,3 +1,3 @@
module gopkg.in/dtapps/go-library.v2/dtime
module github.com/dtapps/go-library/dtime
go 1.16

@ -0,0 +1,11 @@
package duuid_test
import (
v20210726 "github.com/dtapps/go-library/duuid/v20210726"
"log"
"testing"
)
func TestName(t *testing.T) {
log.Println(v20210726.GenUUID())
}

@ -0,0 +1,5 @@
module github.com/dtapps/go-library/duuid
go 1.16
require github.com/google/uuid v1.3.0 // indirect

@ -0,0 +1,2 @@
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=

@ -1,4 +1,4 @@
package uuid
package v20210726
import (
"github.com/google/uuid"

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,5 @@
module github.com/dtapps/go-library/params
go 1.16
require github.com/nilorg/sdk v0.0.0-20210429091026-95b6cdc95c84 // indirect

@ -0,0 +1,2 @@
github.com/nilorg/sdk v0.0.0-20210429091026-95b6cdc95c84 h1:Nxk1uViXfb9MHgtHBlQFWzlQCsJbDQuotfTsAFcFP3o=
github.com/nilorg/sdk v0.0.0-20210429091026-95b6cdc95c84/go.mod h1:X1swpPdqguAZaBDoEPyEWHSsJii0YQ1o+3piMv6W3JU=

@ -1,4 +1,4 @@
package params
package v20210726
import (
"encoding/json"

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -1,22 +0,0 @@
package redis
type Iterator struct {
data []interface{}
index int
}
func NewIterator(data []interface{}) *Iterator {
return &Iterator{data: data}
}
func (i *Iterator) HasNext() bool {
if i.data == nil || len(i.data) == 0 {
return false
}
return i.index < len(i.data)
}
func (i *Iterator) Next() (Ret interface{}) {
Ret = i.data[i.index]
i.index = i.index + 1
return
}

@ -1,65 +0,0 @@
package redis
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
"time"
)
var (
Rdb *redis.Client
RdbC *redis.ClusterClient
)
// InitRedis 初始化连接 普通连接
func InitRedis(host string, port int, password string, db int) (err error) {
dsn := fmt.Sprintf("%s:%v", host, port)
fmt.Printf("【redis.普通】数据库配置 %s \n", dsn)
Rdb = redis.NewClient(&redis.Options{
Addr: dsn,
Password: password, // no password set
DB: db, // use default DB
PoolSize: 100, // 连接池大小
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = Rdb.Ping(ctx).Result()
return err
}
// InitSentinelRedis 初始化连接 哨兵模式
func InitSentinelRedis(adds []string, masterName string, password string, db int) (err error) {
fmt.Printf("【redis.哨兵】数据库配置 %s \n", adds)
Rdb = redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: masterName,
SentinelAddrs: adds,
Password: password, // no password set
DB: db, // use default DB
PoolSize: 100, // 连接池大小
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = Rdb.Ping(ctx).Result()
return err
}
// InitClusterRedis 初始化连接 集群
func InitClusterRedis(adds []string, password string) (err error) {
fmt.Printf("【redis.集群】数据库配置 %v \n", adds)
RdbC = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: adds,
Password: password, // no password set
PoolSize: 100, // 连接池大小
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err = RdbC.Ping(ctx).Result()
return err
}

@ -1,35 +0,0 @@
package redis
import "time"
type empty struct{}
const (
AttrExpr = "expr" //过期时间
AttrNx = "nx" // setNx
)
type OperationAttr struct {
Name string
Value interface{}
}
type OperationAttrs []*OperationAttr
func (a OperationAttrs) Find(name string) interface{} {
for _, attr := range a {
if attr.Name == name {
return attr.Value
}
}
return nil
}
// WithExpire 过期时间
func WithExpire(t time.Duration) *OperationAttr {
return &OperationAttr{Name: AttrExpr, Value: t}
}
func WithNX() *OperationAttr {
return &OperationAttr{Name: AttrNx, Value: empty{}}
}

@ -1,102 +0,0 @@
package redis
import (
"encoding/json"
"github.com/bitly/go-simplejson"
"time"
)
const (
SerializerJson = "json"
SerializerSimpleJson = "simplejson"
SerializerString = "string"
)
type JsonGttFunc func() interface{}
type SimpleJsonGttFunc func() *simplejson.Json
type DBGttFunc func() string
// SimpleCache 缓存
type SimpleCache struct {
Operation *StringOperation // 操作类
Expire time.Duration // 过去时间
DBGetter DBGttFunc // 缓存不存在的操作 DB
JsonGetter JsonGttFunc // 缓存不存在的操作 JSON
SimpleJsonGetter SimpleJsonGttFunc // 缓存不存在的操作 SimpleJson
Serializer string // 序列化方式
}
func NewSimpleCache(operation *StringOperation, expire time.Duration, serializer string) *SimpleCache {
return &SimpleCache{Operation: operation, Expire: expire, Serializer: serializer}
}
// SetCache 设置缓存
func (c *SimpleCache) SetCache(key string, value interface{}) {
c.Operation.Set(key, value, WithExpire(c.Expire)).Unwrap()
}
// GetCache 获取缓存
func (c *SimpleCache) GetCache(key string) (ret interface{}) {
if c.Serializer == SerializerJson {
f := func() string {
obj := c.JsonGetter()
b, err := json.Marshal(obj)
if err != nil {
return ""
}
return string(b)
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
} else if c.Serializer == SerializerString {
f := func() string {
return c.DBGetter()
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
} else if c.Serializer == SerializerSimpleJson {
f := func() string {
obj := c.SimpleJsonGetter()
encode, err := obj.Encode()
if err != nil {
return ""
}
return string(encode)
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
}
return
}
// GetCacheSimpleJson 获取缓存配合SimpleJson插件
func (c *SimpleCache) GetCacheSimpleJson(key string) (js *simplejson.Json) {
if c.Serializer == SerializerJson {
f := func() string {
obj := c.JsonGetter()
b, err := json.Marshal(obj)
if err != nil {
return ""
}
return string(b)
}
ret := c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
js, _ = simplejson.NewJson([]byte(ret))
} else if c.Serializer == SerializerSimpleJson {
f := func() string {
obj := c.SimpleJsonGetter()
encode, err := obj.Encode()
if err != nil {
return ""
}
return string(encode)
}
ret := c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
js, _ = simplejson.NewJson([]byte(ret))
}
return
}

@ -1,30 +0,0 @@
package redis
type SliceResult struct {
Result []interface{}
Err error
}
func NewSliceResult(result []interface{}, err error) *SliceResult {
return &SliceResult{Result: result, Err: err}
}
// Unwrap 空值情况下返回错误
func (r *SliceResult) Unwrap() []interface{} {
if r.Err != nil {
panic(r.Err)
}
return r.Result
}
// UnwrapOr 空值情况下设置返回默认值
func (r *SliceResult) UnwrapOr(defaults []interface{}) []interface{} {
if r.Err != nil {
return defaults
}
return r.Result
}
func (r *SliceResult) Iter() *Iterator {
return NewIterator(r.Result)
}

@ -1,33 +0,0 @@
package redis
import (
"context"
"time"
)
type StringOperation struct {
ctx context.Context
}
func NewStringOperation() *StringOperation {
return &StringOperation{ctx: context.Background()}
}
// Set 设置
func (o *StringOperation) Set(key string, value interface{}, attrs ...*OperationAttr) *StringResult {
exp := OperationAttrs(attrs).Find(AttrExpr)
if exp == nil {
exp = time.Second * 0
}
return NewStringResult(Rdb.Set(o.ctx, key, value, exp.(time.Duration)).Result())
}
// Get 获取单个
func (o *StringOperation) Get(key string) *StringResult {
return NewStringResult(Rdb.Get(o.ctx, key).Result())
}
// MGet 获取多个
func (o *StringOperation) MGet(keys ...string) *SliceResult {
return NewSliceResult(Rdb.MGet(o.ctx, keys...).Result())
}

@ -1,33 +0,0 @@
package redis
type StringResult struct {
Result string
Err error
}
func NewStringResult(result string, err error) *StringResult {
return &StringResult{Result: result, Err: err}
}
// Unwrap 空值情况下返回错误
func (r *StringResult) Unwrap() string {
if r.Err != nil {
panic(r.Err)
}
return r.Result
}
// UnwrapOr 空值情况下设置返回默认值
func (r *StringResult) UnwrapOr(defaults string) string {
if r.Err != nil {
return defaults
}
return r.Result
}
func (r *StringResult) UnwrapOrElse(f func() string) string {
if r.Err != nil {
return f()
}
return r.Result
}

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -1,66 +0,0 @@
package ssh
import (
"fmt"
"golang.org/x/crypto/ssh"
"io"
"net"
"time"
)
// 转发
func sForward(serverAddr string, remoteAddr string, localConn net.Conn, config *ssh.ClientConfig) {
// 设置sshClientConn
sshClientConn, err := ssh.Dial("tcp", serverAddr, config)
if err != nil {
fmt.Printf("ssh.Dial failed: %s", err)
}
// 设置Connection
sshConn, err := sshClientConn.Dial("tcp", remoteAddr)
// 将localConn.Reader复制到sshConn.Writer
go func() {
_, err = io.Copy(sshConn, localConn)
if err != nil {
fmt.Printf("io.Copy failed: %v", err)
}
}()
// 将sshConn.Reader复制到localConn.Writer
go func() {
_, err = io.Copy(localConn, sshConn)
if err != nil {
fmt.Printf("io.Copy failed: %v", err)
}
}()
}
func Tunnel(username string, password string, serverAddr string, remoteAddr string, localAddr string) {
// 设置SSH配置
fmt.Printf("%s服务器%s远程%s本地%s\n", "设置SSH配置", serverAddr, remoteAddr, localAddr)
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
Timeout: 30 * time.Second,
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
// 设置本地监听器
localListener, err := net.Listen("tcp", localAddr)
if err != nil {
fmt.Printf("net.Listen failed: %v\n", err)
}
for {
// 设置本地
localConn, err := localListener.Accept()
if err != nil {
fmt.Printf("localListener.Accept failed: %v\n", err)
}
go sForward(serverAddr, remoteAddr, localConn, config)
}
}

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -1,42 +0,0 @@
package time
import "time"
const (
RFC822Format = "Mon, 02 Jan 2006 15:04:05 MST"
ISO8601Format = "2006-01-02T15:04:05Z"
)
func NowUTCSeconds() int64 { return time.Now().UTC().Unix() }
func NowUTCNanoSeconds() int64 { return time.Now().UTC().UnixNano() }
// GetCurrentDate 获取当前的时间 - 字符串
func GetCurrentDate() string {
return time.Now().Format("2006/01/02 15:04:05")
}
// GetCurrentUnix 获取当前的时间 - Unix时间戳
func GetCurrentUnix() int64 {
return time.Now().Unix()
}
// GetCurrentMilliUnix 获取当前的时间 - 毫秒级时间戳
func GetCurrentMilliUnix() int64 {
return time.Now().UnixNano() / 1000000
}
// GetCurrentNanoUnix 获取当前的时间 - 纳秒级时间戳
func GetCurrentNanoUnix() int64 {
return time.Now().UnixNano()
}
// GetCurrentWjDate 获取当前的时间 - 字符串 - 没有间隔
func GetCurrentWjDate() string {
return time.Now().Format("20060102")
}
func FormatISO8601Date(timestampSecond int64) string {
tm := time.Unix(timestampSecond, 0).UTC()
return tm.Format(ISO8601Format)
}

@ -1,11 +0,0 @@
package time
import "fmt"
func main() {
fmt.Println(GetCurrentDate())
fmt.Println(GetCurrentUnix())
fmt.Println(GetCurrentMilliUnix())
fmt.Println(GetCurrentNanoUnix())
fmt.Println(GetCurrentWjDate())
}

@ -1,14 +0,0 @@
package time
import (
"fmt"
"testing"
)
func TestName(t *testing.T) {
fmt.Println(GetCurrentDate())
fmt.Println(GetCurrentUnix())
fmt.Println(GetCurrentMilliUnix())
fmt.Println(GetCurrentNanoUnix())
fmt.Println(GetCurrentWjDate())
}

@ -0,0 +1,3 @@
module github.com/dtapps/go-library/daes
go 1.16

@ -1,11 +0,0 @@
package uuid_test
import (
"gopkg.in/dtapps/go-library.v2/uuid"
"log"
"testing"
)
func TestName(t *testing.T) {
log.Println(uuid.GenUUID())
}
Loading…
Cancel
Save