util

package
v0.1.1-beta.2 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2023 License: MIT Imports: 20 Imported by: 1

Documentation

Overview

Package utils provides general utils for the project.

Index

Examples

Constants

View Source
const CtxKeyUserID = key(1)

CtxKeyUserID defines context key for user id

Variables

This section is empty.

Functions

func AnonymousUser

func AnonymousUser() int

Site visiting anonymous user

func ArrayStrToInt

func ArrayStrToInt(strArray []string) ([]int, error)

Convert a string array to int array

func ClearDebugToken

func ClearDebugToken()

func Contains

func Contains(strings []string, element string) bool

func ContainsInt

func ContainsInt(ints []int, i int) bool

func CurrentUserID

func CurrentUserID(ctx context.Context) int

func FileExists

func FileExists(path string) bool

func GenerateGUID

func GenerateGUID() string

Generate a guid which is completely random without order

func GenerateUID

func GenerateUID() string

Generate unique id with order. It should be cluster safe.

func GetDebugToken

func GetDebugToken() string

func GetIP

func GetIP(r *http.Request) string

func GetStrVar

func GetStrVar(str string) []string

Get variable from defined brakets. eg "{name} is {realname}" will get ["name", "realname"]

func HandleSendMail

func HandleSendMail(sendMail func(mail MailMessage) error)

func HashPassword

func HashPassword(password string) (string, error)

func IfElse

func IfElse(cond bool, trueV interface{}, falseV interface{}) interface{}

IfElse implements ternary. Equvelant to <cond>?<trueV>:<falseV> in other language. Ref: https://github.com/golang/go/issues/20774 The reason was insane.

There might be performance not perfect, since it needs type convertion.

func InterfaceToStringArray

func InterfaceToStringArray(input []interface{}) []string

func IsAnonymousUser

func IsAnonymousUser(ctx context.Context) bool

func IsIdentifier

func IsIdentifier(input string) bool

func Iterate

func Iterate(strings []string, f func(s string) string) []string

Iterate string slice so it will be easy to do operation inside. eg. make ["1","2"] to be ["a-1", "a-2"]

func ListContains

func ListContains(list []map[string]string, key string, value string) bool

If key exists in a map list

func MatchCondition

func MatchCondition(conditions map[string]interface{}, target map[string]interface{}) (bool, []string)

Iternate condition rules to see if all are matching. If there are keys in condition rules but not in realValues, match fails. * mean always all eg.1) conditions: {id: 12, type:"image"} or {id:[11,12], type:["image", "article"]} target: {id:12,type:"article"} 2) conditions: {id: [11,12], type:"image" } target: {id:[12, 13], type: ["image", "article"]} 3) conditions: {id:11, type: "*"} target: {id:[11, 12], type:"image"} 4) conditions: {id:11, type: "image"} target: {id:[11, 12], type:nil} //nil will be treated as pass

func MatchPassword

func MatchPassword(password string, hash string) bool

func NameToIdentifier

func NameToIdentifier(input string) string

convert name lie "Hello world.?" to "hello-world"

Example
result := GetStrVar("{this} is {good}")
fmt.Println(result[0])
Output:

this

func NewDebugToken

func NewDebugToken(duration time.Duration) string

Generate a debug token and store it into memory, new one will always override existing one After 'duration' it will be removed.

func RandomStr

func RandomStr(n int) []byte

RandomStr generate a random string. no number only small letters.

func ReplaceStrVar

func ReplaceStrVar(str string, values map[string]string) string

Replace variable with values in string

Example
result := ReplaceStrVar("{this} is {value}", map[string]string{"this": "test", "value": "test1"})
fmt.Println(result)
Output:

test is test1

func ResizeImage

func ResizeImage(from string, to string, size string) error

Generate a resized image

func SecurePath

func SecurePath(path string) string

WashPath remove .. make sure it can only go under, not upp

func SendFullMail

func SendFullMail(mailMessage MailMessage) error

Send mail with possible attachments. Note: From in most case(depending on handler) will be from config file Security: attachment needs to be checked to make sure it can not send any file

func SendMail

func SendMail(to []string, subject, body string, bcc ...string) error

Simple sending mail without attachment

func Split

func Split(str string, seperator ...string) []string

Split with triming space. "," is the default separator if no seperator is provided.

func StripSQLPhrase

func StripSQLPhrase(str string) string

Strip unregular string to avoid sql injection. Note this is not used to strip whole sql, but phrase of sql.(eg. ORDER BY ...), not applicable for values.

func UnmarshalData

func UnmarshalData(filepath string, v interface{}) error

UnmarshalData Load json and unmall into variable

func UpperName

func UpperName(input string) string

Convert like "hello_world" to "HelloWorld"

Example
result := UpperName("hello_world")
fmt.Println(result)
Output:

HelloWorld

Types

type MailMessage

type MailMessage struct {
	To          []string //multi to in one mail, for name,use "name<email>" format
	Bcc         []string //bcc
	From        string
	Subject     string
	Body        string
	Attachments []string
}

Directories

Path Synopsis
localmail send mail from local server.
localmail send mail from local server.

Jump to

Keyboard shortcuts

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