utils

package
v0.0.0-...-5049426 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2024 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DTalkMsgText       = "text"       // text message content type
	DTalkMsgLink       = "link"       // link message content type
	DTalkMsgMarkdown   = "markdown"   // markdown message content type
	DTalkMsgActionCard = "actionCard" // action card message content type
	DTalkFeedCard      = "feedCard"   // feed card message content type
)
View Source
const (
	// ContentTypeJson json content type
	ContentTypeJson = "application/json;charset=UTF-8"

	// ContentTypeForm form content type
	ContentTypeForm = "application/x-www-form-urlencoded"
)
View Source
const (
	Day  = time.Hour * 24
	Week = Day * 7
)

Day, week, duration on nanosecond

View Source
const (
	DayMsDur  = Day / time.Millisecond
	WeekMsDur = Week / time.Millisecond
)

Day, week, duration on millisecond

View Source
const (
	DaySecondsDur  = Day / time.Second
	WeekSecondsDur = Week / time.Second
)

Day, week duration on second

View Source
const (
	// DateLayout standery date layout format at day minimum
	DateLayout = "2006-01-02"

	// TimeLayout standery time layout format at second minimum
	TimeLayout = "2006-01-02 15:04:05"

	// HourLayout standery time layout format as hour
	HourLayout = "15:04:05"

	// MSLayout standery time layout format at million second minimum
	MSLayout = "2006-01-02 15:04:05.000"

	// DateNoneHyphen standery time layout format at second minimum without hyphen char
	DateNoneHyphen = "20060102"

	// TimeNoneHyphen standery time layout format at second minimum without hyphen char
	TimeNoneHyphen = "20060102150405"

	// HourNoneHyphen standery time layout format as hour without hyphen char
	HourNoneHyphen = "150405"

	// MSNoneHyphen standery time layout format at million second minimum without hyphen char
	MSNoneHyphen = "20060102150405000"
)

Variables

View Source
var DebugPrintRequest = true

Logout http request url when flag is on, and logger level lowwer than debug.

View Source
var DebugPrintResponse = true

Logout http response datas when flag is on, and logger level lowwer than debug.

View Source
var Nations = map[string]byte{}/* 245 elements not displayed */

All nations informations on ISO 3166-1

@See more visit https://baike.baidu.com/item/ISO%203166-1/5269555?fr=ge_ala

Functions

func AccessAllowOriginByLocal

func AccessAllowOriginByLocal(category int, allowCredentials bool)

Allow cross domain access for localhost, the port number must config in /conf/app.conf file like :

---

; Server port of HTTP
httpport=3200

func AddTask

func AddTask(tname, spec string, f toolbox.TaskFunc)

Add a single monitor task to list

func CardBirthday

func CardBirthday(card string) (*time.Time, error)

Return birthday as time from given ID Card string

func CardGender

func CardGender(card string) (bool, error)

Return gender from given ID Card string, true is male, false is female

func Condition

func Condition(condition bool, trueData any, falseData any) any

Condition return the trueData when pass the condition, or return falseData

`USAGE` :

// use as follow to return diffrent type value, but the input
// true and false params MUST BE no-nil datas.
a := Condition(condition, trueString, falseString)	// return any
b := Condition(condition, trueInt, falseInt).(int)
c := Condition(condition, trueInt64, falseInt64).(int64)
d := Condition(condition, trueFloat, falseFloat).(float64)
e := Condition(condition, trueDur, falseDur).(time.Duration)
f := Condition(condition, trueString, falseString).(string)

func Contain

func Contain(list *[]string, item string) bool

Contain check the given string list if contains item.

You should call Distinct() to filter out the repeat items.

func CopyFile

func CopyFile(src string, dest string) (bool, error)

CopyFile Copy source file to traget file.

func CopyFileTo

func CopyFileTo(src string, dir string) (bool, error)

CopyFileTo copy source file to given dir.

func DayDiff

func DayDiff(start, end time.Time) (int, int, int, int)

DayDiff return diff days, hours, minutes, seconds

func DayUnix

func DayUnix(src int64) int64

DayUnix return the given day unix time at 0:00:00

func DaysUnix

func DaysUnix(days int) int64

DaysUnix return the unix time at 0:00:00, by offset days

func DeleteFile

func DeleteFile(file string) error

DeleteFile delete file

func DeletePath

func DeletePath(dirpath string) error

DeletePath delete files and directory.

func Distinct

func Distinct(src *[]string) []string

Distinct remove duplicate string from given array.

You should call Contain() only for check if exist sub string.

func DurDays

func DurDays(start, end time.Time, format ...string) string

DurDays return readable time during start to end like 2d 6h 25m 48s, you can set the format string, but it must contain 4 %0xd to parse numbers

func DurHours

func DurHours(start, end time.Time, format ...string) string

DurHours return readable time during start to end like 06:25:48, you can see the format string, but it must contain 3 %0xd to parse numbers

func DurNowNs

func DurNowNs(start int64) string

DurNowNs return formated second string from given start in unix nanoseconds

func EncodeUrl

func EncodeUrl(rawurl string) string

EncodeUrl encode url params

func EnsurePath

func EnsurePath(filepath string) error

EnsurePath check the given file path, or create new one if unexist

func FileMD5

func FileMD5(file string) (string, error)

FileMD5 encode file content to md5 string

func FixPath

func FixPath(input string) string

FixPath fix path, example:

---

/aaa/aa\\bb\\cc/d/////     -> /aaa/aa/bb/cc/d
E:/aaa/aa\\bb\\cc/d////e/  -> E:/aaa/aa/bb/cc/d/e
""                         -> .
/                          -> /

func FormatDur

func FormatDur(d time.Duration, layout ...string) string

FormatDur format the time before or after now by add given duration, it may format as TimeLayout when input layout not set, and the formated time contain location timezoom.

func FormatNow

func FormatNow(layout ...string) string

FormatNow format now to given time layout, it may format as TimeLayout when input param not set, and the formated time contain location timezoom.

func FormatTime

func FormatTime(sec int64, nsec ...int64) string

FormatTime format unix time to TimeLayout or MSLayout layout

func FormatUnix

func FormatUnix(layout string, sec int64, nsec ...int64) string

FormatUnix format unix time to given time layout with location timezoom

func GetIP

func GetIP(remoteaddr string) string

GetIP get just ip not port from controller.Ctx.Request.RemoteAddr of beego

func GetLocalIPs

func GetLocalIPs() ([]string, error)

Get all the loacl IP of current deploy machine

func GetSortKey

func GetSortKey(str string) string

GetSortKey get first letter of Chinese Pinyin

func GetTask

func GetTask(tname string) *toolbox.Task

Return task if exist, or nil when unexist

func GetUpperFileDir

func GetUpperFileDir() string

func HourDiff

func HourDiff(start, end time.Time) (int, int, int)

HourDiff return diff hours, minutes, seconds

func HttpClientGet

func HttpClientGet(tagurl string, setRequestFunc SetRequest, params ...any) ([]byte, error)

HttpClientGet handle http get by http.Client, you can set request headers or ignore TLS verfiy of https url by setRequstFunc middle-ware function as :

---

resp, err := comm.HttpClientGet(tagurl, func(req *http.Request) (bool, error) {
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	req.SetBasicAuth("username", "password") // set auther header
	return true, nil  // true is ignore TLS verify of https url
}, "same-params");

func HttpClientGetStruct

func HttpClientGetStruct(tagurl string, setRequestFunc SetRequest, out any, params ...any) error

HttpClientGetStruct handle http get method and unmarshal data to struct object

func HttpClientPost

func HttpClientPost(tagurl string, setRequestFunc SetRequest, postdata ...any) ([]byte, error)

HttpClientPost handle https post by http.Client, you can set request headers or ignore TLS verfiy of https url by setRequstFunc middle-ware function as :

---

resp, err := comm.HttpClientPost(tagurl, func(req *http.Request) (bool, error) {
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	req.SetBasicAuth("username", "password") // set auther header
	return true, nil  // true is ignore TLS verify of https url
}, "post-data")

func HttpClientPostStruct

func HttpClientPostStruct(tagurl string, setRequestFunc SetRequest, out any, postdata ...any) error

HttpClientPostStruct handle http post method and unmarshal data to struct object

func HttpGet

func HttpGet(tagurl string, params ...any) ([]byte, error)

HttpGet handle http get method

func HttpGetString

func HttpGetString(tagurl string, params ...any) (string, error)

HttpGetString call HttpGet and trim " char both begin and end

func HttpGetStruct

func HttpGetStruct(tagurl string, out any, params ...any) error

HttpGetStruct handle http get method and unmarshal data to struct object

func HttpPost

func HttpPost(tagurl string, postdata any, contentType ...string) ([]byte, error)

HttpPost handle http post method, you can set content type as comm.ContentTypeJson or comm.ContentTypeForm, or other you need set.

---

// set post data as json string
data := struct {"key": "Value", "id": "123"}
resp, err := comm.HttpPost(tagurl, data)

// set post data as form string
data := "key=Value&id=123"
resp, err := comm.HttpPost(tagurl, data, comm.ContentTypeForm)

func HttpPostString

func HttpPostString(tagurl string, postdata any, contentType ...string) (string, error)

HttpPostString call HttpPost and trim " char both begin and end.

func HttpPostStruct

func HttpPostStruct(tagurl string, postdata, out any, contentType ...string) error

HttpPostStruct handle http post method and unmarshal data to struct object

func HttpServer

func HttpServer(allowCredentials ...bool)

Start and excute http server base on beego, by default, it just support restful interface not socket.io connection, but you can set allowCredentials as true to on socket.io conect function.

`USAGE` :

// use for restful interface server
func main() {}
	utils.HttpServer()   // or utils.HttpServer(false)

// use for both restful and socket.io server
func main() {
	utils.SocketServer() // or utils.HttpServer(true)
}

func HumanReadable

func HumanReadable(len int64, during int64) string

HumanReadable format the size number of len.

func InstanceOf

func InstanceOf(object any, tagtype reflect.Type) bool

Indicate given object if the target type.

type Car struct {
	Bland string
}
car := &Car{Bland : "H5"}
if comm.Instanceof(car, reflect.TypeOf(&Car{})) {
	// intvalue is int, but target type is string
}

func IsDir

func IsDir(dirpath string) bool

IsDir check whether dir path point to a directory.

func IsDir2

func IsDir2(file *os.File) bool

IsDir2 check whether file point to a directory.

func IsExistFile

func IsExistFile(filepath string) bool

IsExistFile check whether the file exists.

func IsFile

func IsFile(filepath string) bool

IsFile check whether file path point to a file.

func IsFile2

func IsFile2(file *os.File) bool

IsFile2 check whether file point to a file.

func IsSameDay

func IsSameDay(src string, des string) bool

IsSameDay equal given days string based on TimeLayout, the src and des time string must format by time.Format() or offseted timezoom

func IsSameTime

func IsSameTime(src string, des string) bool

IsSameTime equal given time string based on TimeLayout, the src and des time string must format by time.Format() or offseted timezoom

func IsToday

func IsToday(des string) bool

IsToday check the given day string if today, the des time string must format by time.Format() or offseted timezoom

func IsTodayUnix

func IsTodayUnix(des int64) bool

IsTodayUnix check the given time string if today, the des time unix seconds from time.Now() or contian timezoom

func IsVaildIDCard

func IsVaildIDCard(card string) bool

Verify ID Card internal, just simple validate card number only

func IsVaildNation

func IsVaildNation(abbr string) bool

Verify Nation abbreviation if validate on 3 chars

func JoinLines

func JoinLines(inputs ...string) string

JoinLines combine strings into multiple lines

func JoinStrings

func JoinStrings(format string, values []string) string

Join strings with ' ', then insert into the given format string;

- `format` : "SELECT * FROM account WHERE uuid IN (%s)"

- `values` : []string{"D23", "4R", "A34"}

The return is "SELECT * FROM account WHERE uuid IN ('D23','4R','A34')"

func MakeDirs

func MakeDirs(dirpath string, perm ...os.FileMode) error

MakeDirs create new directory, by default perm is 0777.

func MonthUnix

func MonthUnix() int64

MonthUnix return next month day (same as current day of month) unix time at 0:00:00

func MonthsUnix

func MonthsUnix(months int) int64

MonthsUnix return unix time at 0:00:00, by offset months

func NextHalfYear

func NextHalfYear(start ...int64) int64

NextHalfYear return next half a year unix time start from current, or from the given unix seconds and nano seconds

func NextMonth

func NextMonth(start ...int64) int64

NextMonth return next month unix time start from current, or from the given unix seconds and nano seconds

func NextQuarter

func NextQuarter(start ...int64) int64

NextQuarter return next quarter unix time start from current, or from the given unix seconds and nano seconds

func NextTime

func NextTime(duration time.Duration, start ...int64) int64

NextTime return next unix time start from current, or from the given unix seconds and nano seconds

func NextUnix

func NextUnix(duration time.Duration) int64

NextUnix return next 0:00:00 unix time at day after given duration

func NextUnix2

func NextUnix2(years, months, days int) int64

NextUnix2 return next 0:00:00 unix time at day after given years, months and days

func NextWeek

func NextWeek(start ...int64) int64

NextWeek return next week unix time start from current, or from the given unix seconds and nano seconds

func NextYear

func NextYear(start ...int64) int64

NextYear return next year unix time start from current, or from the given unix seconds and nano seconds

func OpenFileTrunc

func OpenFileTrunc(filepath string, perm ...os.FileMode) (*os.File, error)

OpenFileTrunc create new file for trunc content, by default perm is 0666.

func OpenFileWrite

func OpenFileWrite(filepath string, perm ...os.FileMode) (*os.File, error)

OpenFileWrite create new file for write content, by default perm is 0666.

func ParseTime

func ParseTime(layout, src string) (time.Time, error)

ParseTime parse time with zoom, the src time string maybe formated from time.Format() return value.

`WARNING` :

time.Now(), time.Format() are local time with timezoom offset, but time.Parse() parse time string without timezoom just UTC time, you can parse local time by use

time.ParseInLocation(layout, timestring, time.Local).

func QuarterUnix

func QuarterUnix() int64

QuarterUnix return next quarter unix time at 0:00:00

func QuartersUnix

func QuartersUnix(quarters int) int64

QuartersUnix return unix time at 0:00:00, by offset quarters

func ReadPropFile

func ReadPropFile(path string) (map[string]string, error)

ReadPropFile read properties file on filesystem.

func SaveB64File

func SaveB64File(filepath, filename string, b64data string) error

SaveB64File save base64 encoded buffer to target file

func SaveFile

func SaveFile(filepath, filename string, data []byte) error

SaveFile save file buffer to target file

func SocketServer

func SocketServer()

Start and excute both restful and socket.io server

func SplitAfterTrim

func SplitAfterTrim(src, sub string) []string

SplitAfterTrim extend strings.SplitAfter to trim all space chars and sub strings.

// Use Case 1: remove all space chars and filter out sub string items
str := "01/23/34"              // or "/01/23/34", " /01/23/34 / ", "/0 1/23 /34"
utils.SplitAfterTrim(str, "/") // output [01/ 23/ 34/]

// Use Case 2: source string only have space chars or split strings
str := "/"                     // or " / ", " // ", " / / ", " /// "
utils.SplitAfterTrim(str, "/") // output []

`Warning` : DO NOT contain space chars in the sub string!

func SplitTrim

func SplitTrim(src, sub string) []string

SplitTrim extend strings.Split to trim space and sub strings before split.

// Use Case 1: head or end maybe exist space chars or sub strings
str := "01/23/34"         // or " 01/23/34", "01/23/34 ", " 01/23/34 "
                          // or "/01/23/34", "01/23/34/", "/01/23/34/"
                          // or " /01/23/34/ "
utils.SplitTrim(str, "/") // output [01 23 34]

// Use Case 2: source string only have space chars or split strings
str := "/"                // or " /", "/ ", " / ", " // ", " //// "
utils.SplitTrim(str, "/") // output []

func StartTasks

func StartTasks(monitors []*WTask)

Generate tasks and start them as monitors.

func To2Digits

func To2Digits(input any) string

To2Digits fill zero if input digit not enough 2

func To3Digits

func To3Digits(input any) string

To2Digits fill zero if input digit not enough 3

func ToMap

func ToMap(input any) (map[string]any, error)

ToMap transform given struct data to map data, the transform struct feilds must using json tag to mark the map key.

---

type struct Sample {
	Name string `json:"name"`
}
d := Sample{ Name : "name_value" }
md, _ := comm.ToMap(d)
// md data format is {
//     "name" : "name_value"
// }

func ToNDigits

func ToNDigits(input any, n int) string

ToNDigits fill zero if input digit not enough N

func ToXMLReplace

func ToXMLReplace(input any, from, to string) (string, error)

ToXMLReplace transform given struct data to xml string, ant then replace indicated fileds or values, to form param must not empty, but the to param allow set empty when use to remove all form keyworlds.

func ToXMLString

func ToXMLString(input any) (string, error)

ToXMLString transform given struct data to xml string

func Today

func Today() int64

Today return today unix time with offseted location timezoom

func TodayUnix

func TodayUnix() int64

TodayUnix return today unix time at 0:00:00

func Tommorrow

func Tommorrow() int64

Tommorrow return tommorrow unix time srart from current location time

func TommorrowUnix

func TommorrowUnix() int64

TommorrowUnix return tommorrow unix time at 0:00:00

func Try

func Try(do func(), catcher func(error), finaly ...func())

Try try-catch-finaly method

func UpdateChineses

func UpdateChineses(data string, descs []*SvrDesc) (string, error)

Parse total routers and update description on chinese for local server routers, then marshal to string for next to push to nacos config server.

func UpdateRouters

func UpdateRouters(data string) (string, error)

Parse total routers and update description on chinese for local server routers, then marshal to string for next to push to nacos config server.

func VerifyFile

func VerifyFile(fh *multipart.FileHeader, maxBytes ...int64) (string, error)

VerifyFile verify upload file and size, it support jpg/jpeg/JPG/JPEG/png/PNG/mp3/mp4 suffix.

func VerifyFileFormat

func VerifyFileFormat(fh *multipart.FileHeader, format string, size int64) (string, error)

VerifyFileFormat verify upload file and size in MB.

func WeekUnix

func WeekUnix() int64

WeekUnix return next week day (same as current weekday) unix time at 0:00:00

func WeeksUnix

func WeeksUnix(weeks int) int64

WeekUnix return unix time at 0:00:00, by offset weeks

func YearUnix

func YearUnix() int64

YearUnix return next year unix time at 0:00:00

func YearsUnix

func YearsUnix(years int) int64

YearsUnix return unix time at 0:00:00, by offset years

func Yesterday

func Yesterday() int64

Yesterday return yesterday unix time base on current location time

func YesterdayUnix

func YesterdayUnix() int64

YesterdayUnix return yesterday unix time at 0:00:00

Types

type DTActionCard

type DTActionCard struct {
	Title       string `json:"title"`
	Text        string `json:"text"`
	BtnLayer    string `json:"btnOrientation"`
	SingleTitle string `json:"singleTitle"`
	SingleURL   string `json:"singleURL"`
}

type DTAt

type DTAt struct {
	Mobiles []string `json:"atMobiles"`
	UserIDs []string `json:"atUserIds"`
	AtAll   bool     `json:"isAtAll"`
}

type DTButton

type DTButton struct {
	Title     string `json:"title"`
	ActionURL string `json:"actionURL"`
}

type DTFeedCard

type DTFeedCard struct {
	Links []DTFeedLink `json:"links"`
}
type DTFeedLink struct {
	Title  string `json:"title"`
	PicURL string `json:"picURL"`
	MsgURL string `json:"messageURL"`
}
type DTLink struct {
	Title  string `json:"title"`
	Text   string `json:"text"`
	PicURL string `json:"picUrl"`
	MsgURL string `json:"messageUrl"`
}

type DTMarkdown

type DTMarkdown struct {
	Title string `json:"title"`
	Text  string `json:"text"`
}

type DTMsgActionCard

type DTMsgActionCard struct {
	Text    DTActionCard `json:"actionCard"`
	MsgType string       `json:"msgtype"`
}

DTMsgActionCard Action card type message with one click action

type DTMsgFeedCard

type DTMsgFeedCard struct {
	Card    DTFeedCard `json:"feedCard"`
	MsgType string     `json:"msgtype"`
}

DTMsgFeedCard Feed card type message

type DTMsgLink struct {
	Link    DTLink `json:"link"`
	MsgType string `json:"msgtype"`
}

DTMsgLink Link type message

type DTMsgMarkdown

type DTMsgMarkdown struct {
	Text    DTMarkdown `json:"markdown"`
	At      DTAt       `json:"at"`
	MsgType string     `json:"msgtype"`
}

DTMsgMarkdown Markdown type message

type DTMsgSplitAction

type DTMsgSplitAction struct {
	Text    DTSplitAction `json:"actionCard"`
	MsgType string        `json:"msgtype"`
}

DTMsgSplitAction Action card type message with split button actions

type DTMsgText

type DTMsgText struct {
	At      DTAt   `json:"at"`
	Text    DTText `json:"text"`
	MsgType string `json:"msgtype"`
}

DTMsgText Text type message

type DTSplitAction

type DTSplitAction struct {
	Title    string     `json:"title"`
	Text     string     `json:"text"`
	BtnLayer string     `json:"btnOrientation"`
	Btns     []DTButton `json:"btns"`
}

type DTText

type DTText struct {
	Content string `json:"content"`
}

type DTalkSender

type DTalkSender struct {
	WebHook string // custom group chat robot access webhook
	Keyword string // message content keyword filter
	Secure  string // robot secure signature
}

DTalkSender message sender for DingTalk custom robot, it just support inited with keywords, secure token functions, but not ips range sets.

`WARNING` :

Notice that the sender may not success @ anyones of chat's group members when using DingTalk user ids and the target robot have no enterprise ownership, so recommend use DingTalk user phone number to @ anyones or all when you not ensure the robot if have enterprise ownership.

`USAGES` :

the below only show send text type message's usages, the others as same. see more with link https://developers.dingtalk.com/document/robots/custom-robot-access

---

sender := comm.DTalkSender{
	WebHook: "https://oapi.dingtalk.com/robot/send?access_token=xxx",
	Keyword: "FILTERKEY",
	Secure: "SECxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

// at anyones of chat's group members by user phone number
atMobiles := []string{"130xxxxxxxx","150xxxxxxxx"}

// at anyones of chat's group members by user id
atUserIds := []string{"userid1","userid2"}

// Usage 1 :
// send text message filter by keyword without at anyones
sender.SendText("FILTERKEY message content", nil, nil, false)

// Usage 2 :
// send text message filter by keyword and at chat's group anyones
sender.SendText("FILTERKEY message content", nil, atUserIds, false)
sender.SendText("message FILTERKEY content", atMobiles, nil, false)
sender.SendText("message FILTERKEY @130xxxxxxxx content", atMobiles, nil, false)
sender.SendText("message content FILTERKEY", atMobiles, atUserIds, false)

// Usage 3 :
// send text message filter by keyword and at chat's group all members
sender.SendText("FILTERKEY message content", nil, nil, true)

// remove keyword, just using secure token,
// you may using both keyword and secure token too
sender.UsingKey("")

// Usage 4 :
// send text message with secure token
sender.SendText("message content", atMobiles, atUserIds, false, true)
sender.SendText("message content", nil, nil, true, true)
sender.SendText("message content", nil, nil, false, true)

// Usage 5 :
// send text message with secure token and filter by keyword
sender.UsingKey("FILTERKEY2")
sender.SendText("FILTERKEY2 message content", atMobiles, atUserIds, false, true)
sender.SendText("message FILTERKEY2 content", nil, nil, true, true)
sender.SendText("message content FILTERKEY2", nil, nil, false, true)

func (*DTalkSender) SendActionCard

func (s *DTalkSender) SendActionCard(title, text, singleTitle, singleURL string, isSecure ...bool) error

SendActionCard send action card type message, it not support at anyone but has a single link.

`Notice` :

The title, text, singleTitle, singleURL input params must not empty.

`Post Data Format` :

{
	"actionCard": {
		"title": "Hellow",
		"text": "the weather is nice today",
		"btnOrientation": "0",
		"singleTitle" : "Click to chat",
		"singleURL" : "https://actioncard/single/url"
	},
	"msgtype": "actionCard"
}

func (*DTalkSender) SendActionCard2

func (s *DTalkSender) SendActionCard2(title, text string, btns []DTButton, isVertical bool, isSecure ...bool) error

SendActionCard2 send action card type message with multiple buttons.

`Notice` :

The title, text, btns input params must not empty.

And the buttons layout will aways disply as vertical orientation when buttons count over 2, so you can change buttons layout orientation only 2 buttons.

`Post Data Format` :

{
	"msgtype": "actionCard",
	"actionCard": {
		"title": "Hellow",
		"text": "the weather is nice today",
		"btnOrientation": "0",
		"btns": [
			{ "title": "Others",   "actionURL": "https://actioncard/other/url" },
			{ "title": "See more", "actionURL": "https://actioncard/more/url"  }
		]
	}
}

func (*DTalkSender) SendFeedCard

func (s *DTalkSender) SendFeedCard(links []DTFeedLink, isSecure ...bool) error

SendFeedCard send feed card type message, it not support at anyone.

`Notice` :

The all links input params must not empty.

And the buttons layout will aways disply as vertical when the buttons count over 2, so you can change buttons layout orientation only 2 buttons.

`Post Data Format` :

{
	"msgtype":"feedCard",
	"feedCard": {
		"links": [
			{ "title": "Hellow 1", "messageURL": "https://feedcard/message/url/1", "picURL": "https://feedcard/picture1.png" },
			{ "title": "Hellow 2", "messageURL": "https://feedcard/message/url/2", "picURL": "https://feedcard/picture2.png" }
		]
	}
}
func (s *DTalkSender) SendLink(title, text, picURL, msgURL string, isSecure ...bool) error

SendLink send link message, it not support at anyone but have a picture and web link.

`Notice` :

The title, text, msgURL input params must not empty.

`Post Data Format` :

{
	"msgtype": "link",
	"link": {
		"text": "the weather is nice today",
		"title": "Hellow",
		"picUrl": "https://link/picture.png",
		"messageUrl": "https://link/message/url"
	}
}

func (*DTalkSender) SendMarkdown

func (s *DTalkSender) SendMarkdown(title, text string, atMobiles, atUserIds []string, isAtAll bool, isSecure ...bool) error

SendMarkdown send markdown type message, it support anyone and pick, message link urls.

`Notice` :

You MUST add '@130xxxxxxxx' user phone in content string when want to at anyones of chat's group members, and enable change the '@anyone-user' text display position in DintTalk message by move '@130xxxxxxxx' position in content string as:

"text": "### the weather is nice today, '@130xxxxxxxx' is that? \n > yes"
-> `the weather is nice today, {@UserX} is that?
	yes`

`Post Data Format` :

{
	"msgtype": "markdown",
	"markdown": {
		"title": "Hellow",
		"text": "### the weather is nice today \n > yes"
	},
	"at": {
		"atMobiles": [ "150XXXXXXXX" ],
		"atUserIds": [ "user123" ],
		"isAtAll": false
	}
}

func (*DTalkSender) SendText

func (s *DTalkSender) SendText(content string, atMobiles, atUserIDs []string, isAtAll bool, isSecure ...bool) error

SendText send text message, it support at anyones of chat's group members.

`Notice` :

You can change the '@anyone-user' text display position in DintTalk message by add '@130xxxxxxxx' user phone in content string as:

"text": { "content": "the weather is nice today, @130xxxxxxxx is that?" },
-> `the weather is nice today, {@UserX} is that?`

Or the '@anyone-user' text should display as trailing in DingTalk message when content string not contain '@130xxxxxxxx' user phone:

"text": { "content": "the weather is nice today" },
-> `the weather is nice today {@UserX}`

`Post Data Format` :

	{
		"at": {
			"atMobiles": [ "180xxxxxx" ],
			"atUserIds": [ "user123" ],
			"isAtAll": false
		},
		"text": { "content": "the weather is nice today" },
		"msgtype": "text"
}

func (*DTalkSender) SetSecure

func (s *DTalkSender) SetSecure(secure string)

SetSecure set DingTalk sender secure signature, it may remove all leading and trailing white space.

func (*DTalkSender) UsingKey

func (s *DTalkSender) UsingKey(keyword string)

UsingKey using keyword to check message content if valid, it may remove all leading and trailing white space.

type EmailContent

type EmailContent struct {
	Subject string // email title or subject
	Body    string // email body content
}

EmailContent email template

type ExecFunc

type ExecFunc func(data any)

type Group

type Group struct {
	Name   string `json:"group"`  // group name as swagger controller path, like '/v3/acc'
	EnDesc string `json:"endesc"` // english description of group from swagger
	CnDesc string `json:"cndesc"` // chinese description of group manual update by user
}

A group informations

type MailAgent

type MailAgent struct {
	Acc  string `json:"acc"`  // username - mail address
	Pwd  string `json:"pwd"`  // account password
	Host string `json:"host"` // stmp/pop3 host
	Port int    `json:"port"` // stmp/pop3 port
}

MailAgent mail agent informations

`Useage`

---

mailTempleteSubject = "You hava a mail!"
mailTemplateFormat  = `
	<p>
		<span font-weight:bold; style="font-size:16px; color:#363636">Dear</span><br><br>
		<span style="font-size:14px; color:#484848">Your account %s have not activate, please click the follow link to activate it.</span><br>
		<span style="font-size:14px; color:#484848">%s</span><br>
	</p>
	<p align="right">
		<span style="font-size:12px; color:#484848">From %s</span><br>
		<span style="font-size:10px; color:#636363">%s</span>
	</p>
	`

 mailagent = &comm.MailAgent{
     Acc: account, Pwd: password, Host: smtphost, Port: smtpport,
 }
 subject := mailTempleteSubject
 message := fmt.Sprintf(mailTemplateFormat, account, link, who,
     time.Now().Format(templateTimeFormat))
 // send mail with attachment
 // return ma.SendMail(to, subject, message, fileName)
 return ma.SendMail(to, subject, message)

func (*MailAgent) SendAttach

func (a *MailAgent) SendAttach(email EmailContent, mailto, attach string, format ...map[string]string) error

SendAttach send mail with formated map and attach file

func (*MailAgent) SendCode

func (a *MailAgent) SendCode(email EmailContent, mailto string, code string) error

SendCode send verify email with code

The SMS templetes same as:

---

TplEmailRegister = EmailContent{"Account Verify Of XXX", `
<html>
  <body>
    <h3> Dear NAME </h3>
    <p> Thank you for register XXX, the registration verification code is : <h3> TOKEN </h3>, please activate your account in time.</br>
        Please DO NOT forward this code to others. If not myself, please delete this email.</p>
    </br>
    <h5>XXX Technology Co., Ltd</h5>
 </body>
</html>`}

func (*MailAgent) SendFormat

func (a *MailAgent) SendFormat(email EmailContent, mailto string, format ...map[string]string) error

SendFormat send mail with formated map

func (*MailAgent) SendMail

func (a *MailAgent) SendMail(to []string, subject, body string, attach ...string) error

SendMail send email by mail account, it may set attachment from local file

type QTask

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

Task monitor to execute queue tasks in sequence

func GenQTask

func GenQTask(callback TaskCallback, configs ...int) *QTask

Generat a new task monitor instance.

Custom interval duration and interrupt flag by input params as follow:

interrupt := 1  // interrupt to execut the remain tasks when case error
interval := 500 // sleep interval between tasks in microseconds
task := comm.GenTask(callback, interrupt, interval)
task.Post(taskdata)

func (*QTask) Post

func (t *QTask) Post(taskdata any, maxlimits ...int) error

Push a new task to monitor queue back

func (*QTask) SetInterrupt

func (t *QTask) SetInterrupt(interrupt bool)

Set task monitor interrupt filter times

func (*QTask) SetInterval

func (t *QTask) SetInterval(interval int)

Set waiting interval between tasks in microseconds, and it must > 0.

type Queue

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

Queue the type of queue with sync lock

			--------- <- Head
Quere Top : |   1   | -> Pop
			+-------+
			|   2   |
			+-------+
			|  ...  |
			+-------+
	Push -> |   n   | : Queue Back (or Bottom)
			+-------+

func GenQueue

func GenQueue() *Queue

GenQueue generat a new queue instance

func (*Queue) Clear

func (q *Queue) Clear()

Clear clear the queue all data

func (*Queue) Dump

func (q *Queue) Dump()

Dump print out the queue data. this method maybe just use for debug to out put queue items

func (*Queue) Fetch

func (q *Queue) Fetch(callback func(value any) (bool, bool))

Fetch queue nodes, use callback returns to remove node or interupt fetch. Notice that DO NOT do heavy performence codes in callback, exist a lock here!

For example caller code like (Events is a Queue object):

// Try fetch waiting requests to send to idle clusters
h.Events.Fetch(func(request any) (bool, bool) {
	if clusterid := h.getIdleCluster(); clusterid != "" {
		go h.sendRequest(clusterid, request)
		return true /* remove */, false /* continue fetch */
	}

	// Remain request node and interupt fetch
	return false, true
})

func (*Queue) Len

func (q *Queue) Len() int

Len return the length of queue

func (*Queue) Pick

func (q *Queue) Pick() (any, error)

Pick pick but not remove the front data of queue, it will return invar.ErrEmptyData error if the queue is empty

func (*Queue) Pop

func (q *Queue) Pop() (any, error)

Pop pick and remove the front data of queue, it will return invar.ErrEmptyData error if the queue is empty

func (*Queue) Push

func (q *Queue) Push(data any)

Push push a data to queue back if the data not nil

type Router

type Router struct {
	Router string `json:"router"` // restful router full path start /
	Method string `json:"method"` // restful router http method, such as GET, POST...
	Group  string `json:"group"`  // beego controller keyworld
	EnDesc string `json:"endesc"` // english description of router from swagger
	CnDesc string `json:"cndesc"` // chinese description of router manual update by user
}

A router informations

type Routers

type Routers struct {
	CnName  string    `json:"cnname"`  // backend server chinese name
	Groups  []*Group  `json:"groups"`  // groups as swagger controllers
	Routers []*Router `json:"routers"` // routers parsed from swagger.json file
}

All routers of one server

type SetRequest

type SetRequest func(req *http.Request) (bool, error)

SetRequest use for set http request before execute http.Client.Do, you can use this middle-ware to set auth as username and passord, and so on.

@param req Http requester
@return - bool If current request ignore TLS verify or not, false is verify by default.
		- error Exception message

type SmsContent

type SmsContent struct {
	SignName        string
	TemplateCode    string
	TemplatePrefix  string
	TemplateSuffix  string
	TemplateContent string
}

SmsContent sms template

type SmsSender

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

SmsSender sender, including smtp authtication and user info

func NewSmsSender

func NewSmsSender(secret, keyid, requrl string) *SmsSender

NewSmsSender create a sms sender for given cloud service

func (*SmsSender) Send

func (s *SmsSender) Send(phones, signname, tplcode, content string) error

Send sends

func (*SmsSender) SendCode

func (s *SmsSender) SendCode(sms SmsContent, phones string, code string) error

SendCode send verify sms witch code

type Stack

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

Stack the type of stack with sync lock

	Push -> +       + -> Pop
			 \     /
			+-------+
Stack Top : |   n   |
			+-------+
			|  ...  |
			+-------+
			|   2   |
			+-------+
			|   1   | : Stack Bottom
			---------

func GenStack

func GenStack() *Stack

GenStack generat a new stack instance

func (*Stack) Clear

func (s *Stack) Clear()

Clear clear the stack all data

func (*Stack) Dump

func (s *Stack) Dump()

Dump print out the stack data. this method maybe just use for debug to out put stack items

func (*Stack) Len

func (s *Stack) Len() int

Len return the length of stack

func (*Stack) Pick

func (s *Stack) Pick() (any, error)

Pick pick but not remove the top data of stack, it will return invar.ErrEmptyData error if the stack is empty

func (*Stack) Pop

func (s *Stack) Pop() (any, error)

Pop pick and remove the top data of stack, it will return invar.ErrEmptyData error if the stack is empty

func (*Stack) Push

func (s *Stack) Push(data any)

Push push a data to stack top one if the data not nil

type SvrDesc

type SvrDesc struct {
	Server  string            `json:"server"`  // backend server english name
	CnName  string            `json:"cnname"`  // backend server chinese name
	Groups  map[string]string `json:"groups"`  // groups  chinese description
	Routers map[string]string `json:"routers"` // routers chinese description
}

type TaskCallback

type TaskCallback func(data any) error

TaskCallback task callback function

type TimeWheel

type TimeWheel struct {
	sync.Mutex
	// contains filtered or unexported fields
}

TimeWheel delay task sets

func GenTimeWheel

func GenTimeWheel() *TimeWheel

GenTimeWheel generat a new time wheel

func (*TimeWheel) AddDelayTask

func (d *TimeWheel) AddDelayTask(exectime time.Duration, data any, f ExecFunc) error

AddDelayTask insert one new delay task to delay queue

func (*TimeWheel) Start

func (d *TimeWheel) Start()

Start

func (*TimeWheel) Stop

func (d *TimeWheel) Stop()

Stop

type WTask

type WTask struct {
	Name    string           // monitor task name
	Func    toolbox.TaskFunc // monitor task execute function
	Spec    string           // monitor task interval
	ForProd bool             // indicate the task only for prod mode, default no limit
}

Task datas for multipe generate

type WordSegment

type WordSegment struct {
	// contains filtered or unexported fields
}
var GseSegmenter *WordSegment

func SegmentHelper

func SegmentHelper() *WordSegment

func (*WordSegment) CutWord

func (c *WordSegment) CutWord(params string) []string

CutWord split clothes title, save keywords and set keyword weight

Jump to

Keyboard shortcuts

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