goutils

package module
v0.0.0-...-7f81a18 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2022 License: Apache-2.0 Imports: 28 Imported by: 3

README

go-utils

Golang utility library

Documentation

Overview

This is a wrapper of standard http package, exposing out-of-the-box flags like proxy, timeout, json handling.

Index

Constants

This section is empty.

Variables

View Source
var (
	ChinaTimezone = time.FixedZone("Asia/Shanghai", 8*60*60) // In case the deploying machine is not in +8 Timezone.
)

Functions

func Check

func Check(err error)

Check provide a quick way to check unexpected errors that should never happen. It's basically an assertion that once err != nil, fatal panic is thrown.

func CronTick

func CronTick(interval time.Duration) <-chan struct{}

CronTick returns a channel which trigger every *interval* time. It's almost the same as time.Tick, except it align the start time to integer. For example, an interval of 10 minutes, will start in xx:00:00, xx:10:00, etc.

func DCheck

func DCheck(err error)

Check provide a quick way to check unexpected errors that should never happen. It's almost the same as Check(), except only in debug mode will throw panic.

func DedupStrings

func DedupStrings(slice []string) []string

func FetchData

func FetchData(path string) ([]byte, error)

FetchData is a helper function to load local/remote data in the same function. Local: goutils.FetchData("/absolute/path/to/file") Remote: goutils.FetchData("https://www.google.com") Also, it's integrated with proxy in flags. TODO(yuheng): Allow more options, while keeping easy use.

func FetchDataWithContext

func FetchDataWithContext(ctx context.Context, path string) ([]byte, error)

func FetchJson

func FetchJson(path string, resp interface{}) error

FetchJson is a wrapper to call FetchData() and parse results from json.

func FetchJsonWithContext

func FetchJsonWithContext(ctx context.Context, path string, resp interface{}) error

func FetchXml

func FetchXml(path string, resp interface{}) error

FetchXml is a wrapper to call FetchData() and parse results from xml.

func FetchXmlWithContext

func FetchXmlWithContext(ctx context.Context, path string, resp interface{}) error

func GenMask

func GenMask(slice []string) map[string]bool

func Get

func Get(url string) (*http.Response, error)

func GetDownloadClient

func GetDownloadClient() *http.Client

func GetFuncName

func GetFuncName(i interface{}) string

GetFuncName provides shortcut to print the name of any function.

func GetNow

func GetNow() time.Time

func GetWithContext

func GetWithContext(ctx context.Context, url string) (*http.Response, error)

func Init

func Init()

Init need to be execute in the beginning of main() to get PkgInit() to work. NOTE: It already called flag.Parse() alternative method. No need to call flag.Parse() any more.

func IsDebuging

func IsDebuging() bool

IsDebuging returns whether it's in debug mode.

func Jsonify

func Jsonify(v interface{}) string

Jsonify provides shortcut to return an json format string of any varible.

func LogDebug

func LogDebug(v ...interface{})

LogDebug prints info to standard output with [DEBUG] prefix in debug mode.

func LogDebugf

func LogDebugf(msg string, v ...interface{})

Same as LogDebug, except accepting formating info.

func LogError

func LogError(v ...interface{})

LogError prints error to error output with [ERROR] prefix.

func LogErrorDetail

func LogErrorDetail(v ...interface{})

func LogErrorf

func LogErrorf(msg string, v ...interface{})

Same as LogError, except accepting formating info.

func LogFatal

func LogFatal(v ...interface{})

LogFatal prints error to error output with [FATAL] prefix, and terminate the application.

func LogFatalf

func LogFatalf(msg string, v ...interface{})

Same as LogFatal, except accepting formating info.

func LogInfo

func LogInfo(v ...interface{})

LogInfo prints info to standard output with [INFO] prefix.

func LogInfof

func LogInfof(msg string, v ...interface{})

Same as LogInfo, except accepting formating info.

func MatchString

func MatchString(pattern, s string) (matched bool, err error)

MatchString is the same as regexp.MatchString(), except it use the cached version of compiled pattern.

func NewError

func NewError(v ...interface{}) error

NewError returns an error composed like fmt.Sprintf().

func OutputHttpJson

func OutputHttpJson(w http.ResponseWriter, resp interface{})

func OutputHttpOk

func OutputHttpOk(w http.ResponseWriter)

func PkgInit

func PkgInit(f func())

PkgInit is a deferred helper to initialize the package enviornment varible AFTER flags are set. Example usage: >package.go

func init() {
    utils.PkgInit(func() {
        // Your initialization codes here... All flags are available.
    })
}

>main.go

func main() {
    utils.Init()
    // Other codes ...
}

func PostForm

func PostForm(uri string, data map[string]string) (*http.Response, error)

func PostFormWithContext

func PostFormWithContext(ctx context.Context, uri string, data map[string]string) (*http.Response, error)

func PostJson

func PostJson(url string, data interface{}) (*http.Response, error)

func PostJsonWithContext

func PostJsonWithContext(ctx context.Context, url string, data interface{}) (*http.Response, error)

func PrintJson

func PrintJson(v interface{})

PrintJson outputs any varible in Json format to console. Useful for debuging.

func ReverseStringSlice

func ReverseStringSlice(slice []string) []string

func SprintHTML

func SprintHTML(htmlTmpl string, data interface{}) string

func Sprintt

func Sprintt(textTmpl string, data interface{}) string

func StringSliceContains

func StringSliceContains(slice []string, s string) bool

StringSliceContains determines whether a string is contained in another slice. NOTE: This is just a convinient helper. It's computing time complexity is O(N), which may be a performance trap.

func StringSliceIndex

func StringSliceIndex(slice []string, s string) int

func ToTitle

func ToTitle(s string) string

ToTitle converts the first letter of every term in a sentence upper case. It's similar to strings.Title(), except it will only separate strings by space, so that "women's clothes" will be transformed to "Women's Clothes" instead of "Women'S Clothes".

Types

type Monitor

type Monitor struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Monitor is a polling helper to get new updates from external source, by comparing the last modified field. Example Usage:

m := NewMonitor(time.Now(), time.Minute)
for {
    since := m.Next()
    results := dbQuery(table.updated_at, "$gt", since)
    for _, result := range results {
        m.Update(result.LastModified)
        ... Remaining processing
    }
}

func NewMonitor

func NewMonitor(since time.Time, duration time.Duration) (m *Monitor)

func (*Monitor) Next

func (m *Monitor) Next() time.Time

Next returns the latest record time to catch up. Any records with update time later than the return value is regarded new unprocessed records.

func (*Monitor) Update

func (m *Monitor) Update(t time.Time)

Update the modified time of last read record.

type OrderByValue

type OrderByValue []StringIntPair

func (OrderByValue) Len

func (slice OrderByValue) Len() int

func (OrderByValue) Less

func (slice OrderByValue) Less(i, j int) bool

func (OrderByValue) Swap

func (slice OrderByValue) Swap(i, j int)

type Regexp

type Regexp struct {
	*regexp.Regexp
	// contains filtered or unexported fields
}

func CompileRegexp

func CompileRegexp(pattern string) (*Regexp, error)

CompileRegexp is the same as regexp.Compile(), except it cached all the compiled patterns for performance.

func (*Regexp) FindNamedStringSubmatch

func (r *Regexp) FindNamedStringSubmatch(s string) map[string]string

type StringIntPair

type StringIntPair struct {
	Key   string
	Value int
}

func IterStringIntMap

func IterStringIntMap(in map[string]int) []StringIntPair

type Var

type Var map[string]interface{}

Directories

Path Synopsis
Package beanstalkd is a higher level wrapper to utilize beanstalkd as a simple message queue.
Package beanstalkd is a higher level wrapper to utilize beanstalkd as a simple message queue.
Package cache provides MemCache as a TTL based simple cache in memory.
Package cache provides MemCache as a TTL based simple cache in memory.
Package csv provides CsvReader and CsvWriter to process csv format file in the struct declaration style.
Package csv provides CsvReader and CsvWriter to process csv format file in the struct declaration style.
Package flags provide a global flags cache and extends types of flags.
Package flags provide a global flags cache and extends types of flags.
Package mongo provides handful wrapper to access and/or modify the mongo database.
Package mongo provides handful wrapper to access and/or modify the mongo database.
Package presto provides struct declaration style wrapper to access presto result.
Package presto provides struct declaration style wrapper to access presto result.
This package provide a simple way to sample steam data.
This package provide a simple way to sample steam data.
Package sort provides ranking method to easily sort a slice.
Package sort provides ranking method to easily sort a slice.

Jump to

Keyboard shortcuts

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