comm

package
v1.0.18 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2021 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Index

Constants

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
	Month   = Day * 30
	Quarter = Month * 3
	Year    = Day * 365
)

Day, week, month, quarter, year duration on nanosecond

View Source
const (
	DayMs     = Day / time.Millisecond
	WeekMs    = Week / time.Millisecond
	MonthMs   = Month / time.Millisecond
	QuarterMs = Quarter / time.Millisecond
	YearMs    = Year / time.Millisecond
)

Day, week, month, quarter, year duration on millisecond

View Source
const (
	DaySeconds     = Day / time.Second
	WeekSeconds    = Week / time.Second
	MonthSeconds   = Month / time.Second
	QuarterSeconds = Quarter / time.Second
	YearSeconds    = Year / time.Second
)

Day, week, month, quarter, year 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 Segmenter sego.Segmenter

Variables of Sego

Functions

func AccessAllowOriginBy

func AccessAllowOriginBy(category int, origins string)

AccessAllowOriginBy allow cross domain access for the given origins

func AccessAllowOriginByLocal

func AccessAllowOriginByLocal(category int)

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 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 DeleteFile

func DeleteFile(file string) error

DeleteFile delete file

func DeletePath

func DeletePath(dirpath string) error

DeletePath delete files and directory.

func DurDays

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

DurDays return readable time during start to end: 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: 06:25:48, you can se the format string, but it must contain 3 %0xd to parse numbers

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, ep:

/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 FormatNow added in v1.0.18

func FormatNow(layout ...string) string

FormatNow format now to given time layout, it may format as TimeLayout when input param not set.

func FormatUnix added in v1.0.13

func FormatUnix(layout string, unixsec int64, unixnsec ...int64) string

FormatUnix format unix time to given time layout

func GetKeyWords

func GetKeyWords(str string) []string

GetKeyWords get more search keywords

func GetSortKey

func GetSortKey(str string) string

GetSortKey get first letter of Chinese Pinyin

func HourDiff

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

HourDiff return diff hours, minutes, seconds

func HttpClientGet

func HttpClientGet(tagurl string, useTLS bool, params ...interface{}) ([]byte, error)

HttpClientGet handle get by http.Client, you can set useTLS to enable TLS or not

func HttpClientGetStruct

func HttpClientGetStruct(tagurl string, useTLS bool, out interface{}, params ...interface{}) error

HttpClientGetStruct handle http get method and unmarshal data to struct object

func HttpClientPost

func HttpClientPost(tagurl string, useTLS bool, postdata ...interface{}) ([]byte, error)

HttpClientGet handle post by http.Client, you can set useTLS to enable TLS or not

func HttpClientPostStruct

func HttpClientPostStruct(tagurl string, useTLS bool, out interface{}, postdata ...interface{}) error

HttpClientPostStruct handle http post method and unmarshal data to struct object

func HttpGet

func HttpGet(tagurl string, params ...interface{}) ([]byte, error)

HttpGet handle http get method

func HttpGetString

func HttpGetString(tagurl string, params ...interface{}) (string, error)

HttpGetString call HttpGet and trim " char both begin and end

func HttpGetStruct

func HttpGetStruct(tagurl string, out interface{}, params ...interface{}) error

HttpGetStruct handle http get method and unmarshal data to struct object

func HttpPost

func HttpPost(tagurl string, postdata interface{}, 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. [CODE:]

// 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)

[CODE]

func HttpPostString

func HttpPostString(tagurl string, postdata interface{}, contentType ...string) (string, error)

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

func HttpPostStruct

func HttpPostStruct(tagurl string, postdata, out interface{}, contentType ...string) error

HttpPostStruct handle http post method and unmarshal data to struct object

func HumanReadable

func HumanReadable(len int64, during int64) string

HumanReadable format the size number of len.

func IgnoreSysSignalPIPE

func IgnoreSysSignalPIPE()

IgnoreSysSignalPIPE ignore system PIPE signal

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

func IsSameTime

func IsSameTime(src string, des string) bool

IsSameTime equal given time string based on TimeLayout

func IsToday

func IsToday(des string) bool

IsToday check the given day string if today

func IsTodayUnix

func IsTodayUnix(des int64) bool

IsTodayUnix check the given time string if today

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 week unix time at 0:00:00

func NextMonth

func NextMonth() int64

NextMonth return next month unix time start from current

func NextQuarter

func NextQuarter() int64

NextQuarter return next quarter unix time start from current

func NextTime

func NextTime(duration time.Duration) int64

NextTime return next unix time start from current

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() int64

NextWeek return next week unix time start from current

func NextYear

func NextYear() int64

NextYear return next year unix time start from current

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 QuarterUnix

func QuarterUnix() int64

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

func ReadPropFile

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

ReadPropFile read properties file on filesystem.

func RemoveDuplicate

func RemoveDuplicate(oldArr []string) []string

RemoveDuplicate remove duplicate data from array

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 Ternary

func Ternary(condition bool, trueResult interface{}, falseResult interface{}) interface{}

Ternary ternary operation

func To2Digits

func To2Digits(input interface{}) string

To2Digits fill zero if input digit not enough 2

func To3Digits

func To3Digits(input interface{}) string

To2Digits fill zero if input digit not enough 3

func ToMap added in v1.0.15

func ToMap(input interface{}) (map[string]interface{}, error)

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

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

func ToNDigits

func ToNDigits(input interface{}, n int) string

ToNDigits fill zero if input digit not enough N

func ToXMLReplace added in v1.0.16

func ToXMLReplace(input interface{}, 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 added in v1.0.16

func ToXMLString(input interface{}) (string, error)

ToXMLString transform given struct data to xml string

func Today

func Today() int64

Today return today unix time

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

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 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 unix time at 0:00:00

func YearDiff

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

YearDiff return diff years, months, days

func YearUnix

func YearUnix() int64

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

func Yesterday

func Yesterday() int64

Yesterday return yesterday unix time base on current

func YesterdayUnix

func YesterdayUnix() int64

YesterdayUnix return yesterday unix time at 0:00:00

Types

type EmailContent

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

EmailContent email template

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..

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: * [CODE:] * 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>`} * [CODE]

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 Queue

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

Queue the type of queue with sync lock

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) Len

func (q *Queue) Len() int

Len return the length of queue

func (*Queue) Pick

func (q *Queue) Pick() (interface{}, 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() (interface{}, 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 interface{})

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

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

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() (interface{}, 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() (interface{}, 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 interface{})

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

type Task

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

Task the type of task

func GenTask

func GenTask(callback TaskCallback, configs ...int) *Task

GenTask generat a new task instance, you can set the interval duration and interrupt flag as the follow format: [CODE:]

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)

[CODE]

func (*Task) Post

func (t *Task) Post(taskdata interface{})

Post post a task to tasks queue back

func (*Task) SetInterrupt

func (t *Task) SetInterrupt(interrupt bool)

SetInterrupt set interrupt flag

func (*Task) SetInterval

func (t *Task) SetInterval(interval int)

setInterval set wait interval between tasks in microseconds, and it must > 0.

type TaskCallback

type TaskCallback func(data interface{}) error

TaskCallback task callback

Jump to

Keyboard shortcuts

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