Documentation ¶
Index ¶
- Constants
- func AccessAllowOriginByLocal(category int, allowCredentials bool)
- func AddTask(tname, spec string, f toolbox.TaskFunc)
- func CardBirthday(card string) (*time.Time, error)
- func CardGender(card string) (bool, error)
- func Condition(condition bool, trueData any, falseData any) any
- func Contain(list []string, item string) bool
- func ContainInt(list []int, item int) bool
- func ContainInt64(list []int64, item int64) bool
- func ContainInt64s(totals []int64, items []int64) bool
- func ContainInts(totals []int, items []int) bool
- func Contains(totals []string, items []string) bool
- func CopyFile(src string, dest string) (bool, error)
- func CopyFileTo(src string, dir string) (bool, error)
- func DayDiff(start, end time.Time) (int, int, int, int)
- func DayUnix(src int64) int64
- func DaysUnix(days int) int64
- func DeleteFile(file string) error
- func DeletePath(dirpath string) error
- func DistInt64s(src []int64) []int64
- func DistInts(src []int) []int
- func Distinct(src []string) []string
- func DurDays(start, end time.Time, format ...string) string
- func DurHours(start, end time.Time, format ...string) string
- func DurNowNs(start int64) string
- func EncodeUrl(rawurl string) string
- func EnsurePath(filepath string) error
- func ExistInt64s(totals []int64, items []int64) bool
- func ExistInts(totals []int, items []int) bool
- func ExistStrings(totals []string, items []string) bool
- func FileMD5(file string) (string, error)
- func FixPath(input string) string
- func FormatDay(sec int64, layout ...string) string
- func FormatDur(d time.Duration, layout ...string) string
- func FormatNow(layout ...string) string
- func FormatTime(sec int64, nsec ...int64) string
- func FormatToday(layout ...string) string
- func FormatUnix(layout string, sec int64, nsec ...int64) string
- func GetIP(remoteaddr string) string
- func GetLocalIPs() ([]string, error)
- func GetSortKey(str string) string
- func GetTask(tname string) *toolbox.Task
- func GetUpperFileDir() string
- func GetVariable(params any, defvalue any) any
- func HourDiff(start, end time.Time) (int, int, int)
- func HttpClientGet(tagurl string, setRequestFunc SetRequest, params ...any) ([]byte, error)
- func HttpClientGetStruct(tagurl string, setRequestFunc SetRequest, out any, params ...any) error
- func HttpClientPost(tagurl string, setRequestFunc SetRequest, postdata ...any) ([]byte, error)
- func HttpClientPostStruct(tagurl string, setRequestFunc SetRequest, out any, postdata ...any) error
- func HttpGet(tagurl string, params ...any) ([]byte, error)
- func HttpGetString(tagurl string, params ...any) (string, error)
- func HttpGetStruct(tagurl string, out any, params ...any) error
- func HttpPost(tagurl string, postdata any, contentType ...string) ([]byte, error)
- func HttpPostString(tagurl string, postdata any, contentType ...string) (string, error)
- func HttpPostStruct(tagurl string, postdata, out any, contentType ...string) error
- func HttpServer(allowCredentials ...bool)
- func HumanReadable(len int64, during int64) string
- func InstanceOf(object any, tagtype reflect.Type) bool
- func IsDir(dirpath string) bool
- func IsDir2(file *os.File) bool
- func IsExistFile(filepath string) bool
- func IsFile(filepath string) bool
- func IsFile2(file *os.File) bool
- func IsSameDay(src string, des string) bool
- func IsSameTime(src string, des string) bool
- func IsToday(des string) bool
- func IsTodayUnix(des int64) bool
- func IsVaildIDCard(card string) bool
- func IsVaildNation(abbr string) bool
- func JoinFloats(nums []float64, sep ...string) string
- func JoinInt64s(nums []int64, sep ...string) string
- func JoinInts(nums []int, sep ...string) string
- func JoinLines(inputs ...string) string
- func MakeDirs(dirpath string, perm ...os.FileMode) error
- func MonthUnix() int64
- func MonthsUnix(months int) int64
- func NextHalfYear(start ...int64) int64
- func NextMonth(start ...int64) int64
- func NextQuarter(start ...int64) int64
- func NextTime(duration time.Duration, start ...int64) int64
- func NextUnix(duration time.Duration) int64
- func NextUnix2(years, months, days int) int64
- func NextWeek(start ...int64) int64
- func NextYear(start ...int64) int64
- func OpenFileTrunc(filepath string, perm ...os.FileMode) (*os.File, error)
- func OpenFileWrite(filepath string, perm ...os.FileMode) (*os.File, error)
- func ParseTime(layout, src string) (time.Time, error)
- func QuarterUnix() int64
- func QuartersUnix(quarters int) int64
- func ReadPropFile(path string) (map[string]string, error)
- func ReverInt64s(src string, sep ...string) []int64
- func ReverInts(src string, sep ...string) []int
- func SaveB64File(filepath, filename string, b64data string) error
- func SaveFile(filepath, filename string, data []byte) error
- func SilentClientGet(tagurl string, setRequestFunc SetRequest, params ...any) ([]byte, error)
- func SilentClientGetStruct(tagurl string, setRequestFunc SetRequest, out any, params ...any) error
- func SilentClientPost(tagurl string, setRequestFunc SetRequest, postdata ...any) ([]byte, error)
- func SilentClientPostStruct(tagurl string, setRequestFunc SetRequest, out any, postdata ...any) error
- func SilentGet(tagurl string, params ...any) ([]byte, error)
- func SilentGetString(tagurl string, params ...any) (string, error)
- func SilentGetStruct(tagurl string, out any, params ...any) error
- func SilentPost(tagurl string, postdata any, contentType ...string) ([]byte, error)
- func SilentPostString(tagurl string, postdata any, contentType ...string) (string, error)
- func SilentPostStruct(tagurl string, postdata, out any, contentType ...string) error
- func SocketServer()
- func SplitAfterTrim(src, sub string) []string
- func SplitTrim(src, sub string) []string
- func StartTasks(monitors []*WTask)
- func To2Digits(input any) string
- func To3Digits(input any) string
- func ToMap(input any) (map[string]any, error)
- func ToNDigits(input any, n int) string
- func ToXMLReplace(input any, from, to string) (string, error)
- func ToXMLString(input any) (string, error)
- func Today() int64
- func TodayUnix() int64
- func Tommorrow() int64
- func TommorrowUnix() int64
- func TrimEmpty(src []string) []string
- func Try(do func(), catcher func(error), finaly ...func())
- func UpdateChineses(data string, descs []*SvrDesc) (string, error)
- func UpdateRouters(data string) (string, error)
- func VarInt(src []int, def int) int
- func VarInt64(src []int64, def int64) int64
- func VarString(src []string, def string) string
- func VerifyFile(fh *multipart.FileHeader, maxBytes ...int64) (string, error)
- func VerifyFileFormat(fh *multipart.FileHeader, format string, size int64) (string, error)
- func WeekUnix() int64
- func WeeksUnix(weeks int) int64
- func YearUnix() int64
- func YearsUnix(years int) int64
- func Yesterday() int64
- func YesterdayUnix() int64
- type DTActionCard
- type DTAt
- type DTButton
- type DTFeedCard
- type DTFeedLink
- type DTLink
- type DTMarkdown
- type DTMsgActionCard
- type DTMsgFeedCard
- type DTMsgLink
- type DTMsgMarkdown
- type DTMsgSplitAction
- type DTMsgText
- type DTSplitAction
- type DTText
- type DTalkSender
- func (s *DTalkSender) SendActionCard(title, text, singleTitle, singleURL string, isSecure ...bool) error
- func (s *DTalkSender) SendActionCard2(title, text string, btns []DTButton, isVertical bool, isSecure ...bool) error
- func (s *DTalkSender) SendFeedCard(links []DTFeedLink, isSecure ...bool) error
- func (s *DTalkSender) SendLink(title, text, picURL, msgURL string, isSecure ...bool) error
- func (s *DTalkSender) SendMarkdown(title, text string, atMobiles, atUserIds []string, isAtAll bool, ...) error
- func (s *DTalkSender) SendText(content string, atMobiles, atUserIDs []string, isAtAll bool, isSecure ...bool) error
- func (s *DTalkSender) SetSecure(secure string)
- func (s *DTalkSender) UsingKey(keyword string)
- type EmailContent
- type EmptyStruct
- type ExecFunc
- type Group
- type MailAgent
- func (a *MailAgent) SendAttach(email EmailContent, mailto, attach string, format ...map[string]string) error
- func (a *MailAgent) SendCode(email EmailContent, mailto string, code string) error
- func (a *MailAgent) SendFormat(email EmailContent, mailto string, format ...map[string]string) error
- func (a *MailAgent) SendMail(to []string, subject, body string, attach ...string) error
- type QTask
- type Queue
- func GenQueue() *Queuedeprecated
- func NewQueue() *Queue
- type Router
- type Routers
- type SetRequest
- type Sets
- func (s *Sets) Add(value any) *Sets
- func (s *Sets) AddInt64s(values []int64) *Sets
- func (s *Sets) AddInts(values []int) *Sets
- func (s *Sets) AddSets(other *Sets) *Sets
- func (s *Sets) AddStrings(values []string) *Sets
- func (s *Sets) Adds(values ...any) *Sets
- func (s *Sets) Array() []any
- func (s *Sets) ArrayInt() []int
- func (s *Sets) ArrayInt64() []int64
- func (s *Sets) ArrayString() []string
- func (s *Sets) Clear() *Sets
- func (s *Sets) Contain(value any) bool
- func (s *Sets) ContainInt64s(values []int64) bool
- func (s *Sets) ContainInts(values []int) bool
- func (s *Sets) ContainSets(other *Sets) bool
- func (s *Sets) ContainStrings(values []string) bool
- func (s *Sets) Contains(values ...any) bool
- func (s *Sets) ExistInt64s(values []int64) bool
- func (s *Sets) ExistInts(values []int) bool
- func (s *Sets) ExistStrings(values []string) bool
- func (s *Sets) Exists(values ...any) bool
- func (s *Sets) Fetch(scaning func(e any) bool)
- func (s *Sets) Remove(value any) *Sets
- func (s *Sets) RemoveInt64s(values []int64) *Sets
- func (s *Sets) RemoveInts(values []int) *Sets
- func (s *Sets) RemoveSets(other *Sets) *Sets
- func (s *Sets) RemoveStrings(values []string) *Sets
- func (s *Sets) Removes(values ...any) *Sets
- type SmsContent
- type SmsSender
- type Stack
- func GenStack() *Stackdeprecated
- func NewStack() *Stack
- type SvrDesc
- type TaskCallback
- type TimeWheel
- type WTask
- type WordSegment
Constants ¶
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 )
const ( // ContentTypeJson json content type ContentTypeJson = "application/json;charset=UTF-8" // ContentTypeForm form content type ContentTypeForm = "application/x-www-form-urlencoded" )
const ( Day = time.Hour * 24 Week = Day * 7 )
Day, week, duration on nanosecond
const ( DayMsDur = Day / time.Millisecond WeekMsDur = Week / time.Millisecond )
Day, week, duration on millisecond
Day, week duration on second
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 ¶
This section is empty.
Functions ¶
func AccessAllowOriginByLocal ¶
Allow cross domain access for localhost, the port number must config in /conf/app.conf file like :
---
; Server port of HTTP httpport=3200
func CardBirthday ¶
Return birthday as time from given ID Card string
func CardGender ¶
Return gender from given ID Card string, true is male, false is female
func Condition ¶
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 ¶
Contain check the given string list if contains item.
You should call Distinct() to filter out the repeat items.
func ContainInt ¶
Contain check the given int list if contains item.
func ContainInt64 ¶
Contain check the given int64 list if contains item.
func ContainInt64s ¶
ContainInt64s check the given int64 items if contains in totals.
func ContainInts ¶
ContainInts check the given int items if contains in totals.
func CopyFileTo ¶
CopyFileTo copy source file to given dir.
func DistInt64s ¶
Distinct remove duplicate int64 from given array.
func Distinct ¶
Distinct remove duplicate string from given array.
You should call Contain() only for check if exist sub string.
func DurDays ¶
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 ¶
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 EnsurePath ¶
EnsurePath check the given file path, or create new one if unexist
func ExistInt64s ¶
ExistInt64s check the given int64 items if any exist in totals.
func ExistStrings ¶
ExistStrings check the given string items if any exist in totals.
func FixPath ¶
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 FormatDay ¶
FormatDay format day string from given unix seconds as '2006-01-02', or custom format like '2006/01/02', '2006.01.02' and so on.
func FormatDur ¶
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 ¶
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 ¶
FormatTime format unix time to TimeLayout or MSLayout layout
func FormatToday ¶
FormatToday format now to today string as '2006-01-02', or custom format set by layout like '2006/01/02', '2006.01.02' and so on.
func FormatUnix ¶
FormatUnix format unix time to given time layout with location timezoom
func GetLocalIPs ¶
GetLocalIPs get all the loacl IP of current deploy machine
func GetUpperFileDir ¶
func GetUpperFileDir() string
func GetVariable ¶
Check the variable params, return the first value if exist any, or return default string, int, int64.
`USAGE` :
func sample(params ...string) { a := GetVariable(params, "def-value").(string) // Do saming here }
see utils.VarString() to string type only.
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 HttpGetString ¶
HttpGetString call HttpGet and trim " char both begin and end
func HttpGetStruct ¶
HttpGetStruct handle http get method and unmarshal data to struct object
func HttpPost ¶
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 ¶
HttpPostString call HttpPost and trim " char both begin and end.
func HttpPostStruct ¶
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 ¶
HumanReadable format the size number of len.
func InstanceOf ¶
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 IsExistFile ¶
IsExistFile check whether the file exists.
func IsSameDay ¶
IsSameDay equal given days string based on TimeLayout, the src and des time string must format by time.Format() or offseted timezoom
func IsSameTime ¶
IsSameTime equal given time string based on TimeLayout, the src and des time string must format by time.Format() or offseted timezoom
func IsToday ¶
IsToday check the given day string if today, the des time string must format by time.Format() or offseted timezoom
func IsTodayUnix ¶
IsTodayUnix check the given time string if today, the des time unix seconds from time.Now() or contian timezoom
func IsVaildIDCard ¶
Verify ID Card internal, just simple validate card number only
func IsVaildNation ¶
Verify Nation abbreviation if validate on 3 chars
func JoinFloats ¶
JoinFloats join float64 numbers as string '0.1,2,3.45' with ',' default separator, or custom separator '-' like '0.1-2-3.45'.
func JoinInt64s ¶
JoinInt64s join int64 numbers as string '1,2,3' with ',' default separator, or custom separator '-' like '1-2-3'.
func JoinInts ¶
JoinInts join int numbers as string '1,2,3' with ',' default separator, or custom separator '-' like '1-2-3'.
func MonthUnix ¶
func MonthUnix() int64
MonthUnix return next month day (same as current day of month) unix time at 0:00:00
func MonthsUnix ¶
MonthsUnix return unix time at 0:00:00, by offset months
func NextHalfYear ¶
NextHalfYear return next half a year unix time start from current, or from the given unix seconds and nano seconds
func NextMonth ¶
NextMonth return next month unix time start from current, or from the given unix seconds and nano seconds
func NextQuarter ¶
NextQuarter return next quarter unix time start from current, or from the given unix seconds and nano seconds
func NextTime ¶
NextTime return next unix time start from current, or from the given unix seconds and nano seconds
func NextWeek ¶
NextWeek return next week unix time start from current, or from the given unix seconds and nano seconds
func NextYear ¶
NextYear return next year unix time start from current, or from the given unix seconds and nano seconds
func OpenFileTrunc ¶
OpenFileTrunc create new file for trunc content, by default perm is 0666.
func OpenFileWrite ¶
OpenFileWrite create new file for write content, by default perm is 0666.
func ParseTime ¶
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 QuartersUnix ¶
QuartersUnix return unix time at 0:00:00, by offset quarters
func ReadPropFile ¶
ReadPropFile read properties file on filesystem.
func ReverInt64s ¶
Reversal int64s string to int64 array with default separator , char or custom separator.
func ReverInts ¶
Reversal ints string to int array with default separator , char or custom separator.
func SaveB64File ¶
SaveB64File save base64 encoded buffer to target file
func SilentClientGet ¶
func SilentClientGet(tagurl string, setRequestFunc SetRequest, params ...any) ([]byte, error)
SilentClientGet call httpUtils.ClientGet() on silent state
func SilentClientGetStruct ¶
func SilentClientGetStruct(tagurl string, setRequestFunc SetRequest, out any, params ...any) error
SilentClientGetStruct call httpUtils.ClientGetStruct() on silent state
func SilentClientPost ¶
func SilentClientPost(tagurl string, setRequestFunc SetRequest, postdata ...any) ([]byte, error)
SilentClientPost call httpUtils.ClientPost() on silent state
func SilentClientPostStruct ¶
func SilentClientPostStruct(tagurl string, setRequestFunc SetRequest, out any, postdata ...any) error
SilentClientPostStruct call httpUtils.ClientPostStruct() on silent state
func SilentGetString ¶
SilentGetString call httpUtils.GetString() on silent state
func SilentGetStruct ¶
SilentGetStruct call httpUtils.GetStruct() on silent state
func SilentPost ¶
SilentPost call httpUtils.Post() on silent state
func SilentPostString ¶
SilentPostString call httpUtils.PostString() on silent state
func SilentPostStruct ¶
SilentPostStruct call httpUtils.PostStruct() on silent state
func SplitAfterTrim ¶
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 ¶
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 ToMap ¶
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 ToXMLReplace ¶
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 ¶
ToXMLString transform given struct data to xml string
func Tommorrow ¶
func Tommorrow() int64
Tommorrow return tommorrow unix time srart from current location time
func UpdateChineses ¶
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 ¶
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 ¶
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
Types ¶
type DTActionCard ¶
type DTFeedCard ¶
type DTFeedCard struct {
Links []DTFeedLink `json:"links"`
}
type DTFeedLink ¶
type DTMarkdown ¶
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 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 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 (*DTalkSender) SendLink ¶
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 EmptyStruct ¶
type EmptyStruct struct{}
Empty struct regard as map value occupy 0 memery size to simulate sets type.
var sets = map[string]EmptyStruct{ "set value 1": utils.E_, "set value 2": struct{}{}, }
var E_ EmptyStruct
Empty map value for simulate Set type.
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
type QTask ¶
type QTask struct {
// contains filtered or unexported fields
}
Task monitor to execute queue tasks in sequence
func GenQTask
deprecated
func GenQTask(callback TaskCallback, configs ...int) *QTask
Deprecated: use utils.NewQTask instead it.
func NewQTask ¶
func NewQTask(callback TaskCallback, configs ...int) *QTask
Create 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 := utils.NewTask(callback, interrupt, interval) task.Post(taskdata)
func (*QTask) SetInterrupt ¶
Set task monitor interrupt filter times
func (*QTask) SetInterval ¶
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 (*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 ¶
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) Pick ¶
Pick pick but not remove the front data of queue, it will return invar.ErrEmptyData error if the queue is empty
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 ¶
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 Sets ¶
type Sets struct {
// contains filtered or unexported fields
}
Sets type for cache different types and unique value datas.
func (*Sets) AddStrings ¶
Add the string array values to sets if not exist.
func (*Sets) Adds ¶
Add the values to sets if not exist.
utils.NewSets().Adds(1, "2", byte(3)) vs := []any{1, "2", byte(3)} utils.NewSets().Adds(vs...)
func (*Sets) ArrayInt64 ¶
Return all exist int64 values as unorderd int64 array.
func (*Sets) ArrayString ¶
Return all exist string values as unorderd string array.
func (*Sets) ContainInt64s ¶
Check the int64 array values if contain in self sets.
func (*Sets) ContainInts ¶
Check the int array values if contain in self sets.
func (*Sets) ContainSets ¶
Check the sets values if contain in self sets.
func (*Sets) ContainStrings ¶
Check the string array values if contain in self sets.
func (*Sets) Contains ¶
Check the values if contain in self sets.
ok := utils.NewSets().Adds(1, "2", byte(3)).Contains(1, "2") vs := []any{"2", byte(3)} ok := utils.NewSets().Adds(1, "2", byte(3)).Contains(vs...)
func (*Sets) ExistInt64s ¶
Check the int64 array values if any one exist in self sets.
func (*Sets) ExistStrings ¶
Check the string array values if any one exist in self sets.
func (*Sets) Exists ¶
Check the values if any one exist in self sets.
ok := utils.NewSets().Adds(1, "2", byte(3)).Exists(1, "2") vs := []any{"2", byte(3)} ok := utils.NewSets().Adds(1, "2", byte(3)).Exists(vs...)
func (*Sets) RemoveInt64s ¶
Remove the int64 values from self sets.
func (*Sets) RemoveInts ¶
Remove the int values from self sets.
func (*Sets) RemoveSets ¶
Remove the sets values from self sets.
func (*Sets) RemoveStrings ¶
Remove the string values from self sets.
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 ¶
NewSmsSender create a sms sender for given cloud service
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 (*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) Pick ¶
Pick pick but not remove the top data of stack, it will return invar.ErrEmptyData error if the stack is empty
type TimeWheel ¶
TimeWheel delay task sets
func (*TimeWheel) AddDelayTask ¶
AddDelayTask insert one new delay task to delay queue
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