pgo

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2024 License: MIT Imports: 29 Imported by: 1

README

pgo

Go library for PHP community with convenient functions

Mentioned in Awesome Go Go Report Card Build and test codecov GoDoc

Installation

Via go get command:

go get github.com/arthurkushman/pgo

Imagine that you need to write Go code every day and also have a convenient functions in memory from PHP experience

Core
Serialize/Unserialize

For instance, to store Go code data in storage engines like rdbms, no-sql, key-value etc, you can use serialization functions to serialize Go code to string and unserialize it back from string to Go code:

m := make(map[int]string)
m[0] = "abc"

str, err := pgo.Serialize(m) // str -> "Dv+BBAEC/4IAAQQBDAAACf+CAAEAA2FiYw=="

unserMap := make(map[int]string)
err = pgo.Unserialize(str, &unserMap) // unserMap -> map[int]string{0: "abc"}
Date

You can use date function with similar formatting for PHP e.g.:

dateStr := pgo.Date("Y-m-d H:i:s") // 2019-03-28 12:23:03

pgo.Date("j D, M") // 27 Wed, Mar

pgo.Date("Q") // 3 (of 1,2,3,4 quarters)
Milli/Micro
nowMicro := pgo.UnixMicro() // get current unix microseconds
nowMilli := pgo.UnixMilli() // get current unix milliseconds

// get current millis + 3ms 
nowMillisPlusThree := pgo.Time(time.Now().Add(time.Millisecond * 3)).Milliseconds()
// get current microseconds + 7μs 
nowMicroPlusSeven := pgo.Time(now.Add(time.Microsecond * 7)).Microseconds()
Strings
StrReplace

replace sub-strings with StrReplace:

subject := "The quick brown fox jumped over the lazy dog"

str, err := pgo.StrReplace([]string{"fox", "dog"}, []string{"cat", "elephant"}, subject)

// and if case-insensitive replace needed - pgo.StrIReplace([]string{"DOG", "QuiCK"}, []string{"fox", "slow"}, subject) 
HTTPBuildQuery

Building a http query string:

queryStr := pgo.HTTPBuildQuery(map[string]interface{}{
  "foo":      "bar",
  "bar":      "baz",
  "s":        []string{"1", "foo", "2", "bar", "3", "baz"},
  "num":      123,
  "bigNum":   int64(1238873737737737373),
  "amount":   623.937,
  "isActive": true,
}) // amount=623.937&bar=baz&bigNum=1238873737737737373&foo=bar&isActive=true&num=123&s=1&s=foo&s=2&s=bar&s=3&s=baz
StripTags

Strip tags with exclusion rules:

html := "<div>Lorem <span>ipsum dolor sit amet</span>, consectetur adipiscing elit, sed do eiusmod <a href=\"http://example.com\">tempor incididunt</a> ut labore <strong>et dolore</strong> magna aliqua.</div>"

str := html.StripTags(html, []string{"a", "span"}) // results in: "Lorem <span>ipsum dolor sit amet</span>, consectetur adipiscing elit, sed do eiusmod <a href=\"http://example.com\">tempor incididunt</a> ut labore et dolore magna aliqua."

UPD: As had been stated here - https://github.com/golang/go/issues/22639 There is a very handy "stripTags" function in html/template, then guys from official team as fast as they got dislike on their negative comment, closed the thread. That is why libs like pgo is appearing and will be move forward/evolve, bypassing strict rules that sometimes looking nonsence.

Files
FileGetContents

Read files with offset/limit:

content, err := pgo.FileGetContents("somefile.txt", 0, 1024)
FilePutContents

reflexively write to files with:

n, err := pgo.FilePutContents("somefile.txt", strToWrite, pgo.FileAppend)

Read from context (via http(s)):

content, err := pgo.FileGetContents("http://google.com", pgo.NewContext())
MoveUploadedFile

Uploading files from web-forms to your server:

ctx := pgo.NewContext()
ctx.Req = YourReq
ctx.UploadMaxFileSize = 10 << 25

uploaded := ctx.MoveUploadedFile("foo", "/srv/images/pic123.png")
FileExists

Checking for file existence

if pgo.FileExists("file1.txt") == true {
// do something with existent file
}

Check if it is file/dir/symlink

if pgo.IsFile("someFile.txt") {
	// do something with file
}

if pgo.IsDir("someDir/") {
	// do something with dir
}

if pgo.IsLink("someLink") {
	// do somthing with symlink
}
Arrays
InArray

Check if an array contains an element

pgo.InArray(3, []int{1, 2, 3}) // true
pgo.InArray("bar33", []string{"foo", "bar", "baz"}) // false
pgo.InArray(3.14159, []float64{33.12, 12.333, 3.14159, 78.4429}) // true
ArrayChunk

Split an array by chunks (with auto-tailing)

pgo.ArrayChunk([]int{1, 2, 3, 4, 5, 6, 7, 8}, 2) // [][]int{[]int{1, 2}, []int{3, 4}, []int{5, 6}, []int{7, 8}}

pgo.ArrayChunk([]string{"foo", "bar", "baz", "fizz", "buzz"}, 3) // [][]string{[]string{"foo", "bar", "baz"}, []string{"fizz", "buzz"}}
ArrayCombine

Create an array by using one array for keys and another for its values

pgo.ArrayCombine([]int{11, 32, 13, 14, 51, 46, 17, 88}, []string{"foo", "bar", "baz", "fizz", "buzz", "mazz", "freez", "lorum"})
/*
   map[int]string{
   		11: "foo",
   		32: "bar",
   		13: "baz",
   		14: "fizz",
   		51: "buzz",
   		46: "mazz",
   		17: "freez",
   		88: "lorum",
   	}
*/
pgo.ArrayCombine([]string{"foo", "bar", "baz", "fizz", "buzz"}, []float64{11.32, 32.42, 13.246, 14.41, 51.98})
/*
map[string]float64{
			"foo":  11.32,
			"bar":  32.42,
			"baz":  13.246,
			"fizz": 14.41,
			"buzz": 51.98,
		}
*/
ArrayCountValues

Count all the values of an array/slice

pgo.ArrayCountValues([]string{"foo", "bar", "foo", "baz", "bar", "bar"}) // map[string]int{"foo": 2, "bar": 3, "baz": 1}

pgo.ArrayCountValues([]float64{3.14159, 43.03, 8, 3.14159, 43.02, 8}) // map[float64]int{3.14159: 2, 8: 2, 43.03: 1, 43.02: 1}
ArrayMap

Apply the callback to the elements of the given arrays

pgo.ArrayMap([]string{"foo", "bar", "baz"}, func (v string) string {
return strings.ToUpper(v)
}) // []string{"FOO", "BAR", "BAZ"}

pgo.ArrayMap([]float64{1, 2, 3, 4, 5}, func (v float64) float64 {
return math.Pow(v, 2)
}) // []float64{1, 4, 9, 16, 25}
ArrayFilter

filters elements of an array using a callback function

pgo.ArrayFilter([]float64{1, 2, 3, 4, 5}, func (v float64) bool {
return v > 2.718
}) // []float64{3, 4, 5}
ArrayDiff

returns the values in array1 that are not present in any of the other arrays

pgo.ArrayDiff([]string{"foo", "bar", "fizz", "baz"}, []string{"foo", "bar"}) // []string{"fizz", "baz"}
pgo.ArrayDiff([]int{3, 43, 8, 4, 9}, []int{3, 8, 9, 4}) // []int{43}
ArrayUdiff

computes the difference of arrays by using a callback function for data comparison

pgo.ArrayUdiff(func (a interface{}, b interface{}) int {
  if a.(string) > b.(string) {
    return 1
  } else if a.(string) < b.(string) {
    return -1
  }

  return 0
}, []string{"foo", "bar", "fizz", "baz"}, []string{"foo", "bar"}) // []string{"fizz", "baz"}

pgo.ArrayUdiff(func (a interface{}, b interface{}) int {
  if a.(int) > b.(int) {
      return 1
  } else if a.(int) < b.(int) {
      return -1
  }
  
  return 0
}, []int{3, 43, 8, 4, 9}, []int{3, 8, 9, 4}) // []int{43}
ArraySum

calculate the sum of values in an array

pgo.ArraySum([]int{12, 54, 32, 12, 33}) // int: 143
ArrayIntersect

computes the intersection of arrays

pgo.ArrayIntersect([]int{12, 54, 32, 12, 33}, []int{3, 12, 54, 9}, []int{12, 33, 9}) // []int{12, 54, 33}

pgo.ArrayIntersect([]string{"foo", "bar", "baz", "fizz", "bazz", "fizz", "fizz"}, []string{"bar", "fizz"}, []string{"foo", "bar", "hey"}) // []string{"foo", "bar", "fizz"}
ArrayMin/ArrayMax

finds minimum/maximum value from []T

res = pgo.ArrayMax([]int{3, 1, 2, 9}) // res == 9
res = pgo.ArrayMax([]float64{-3.12, -1.678, -2.01, -9.007}) // res == -1.678
res = pgo.ArrayMin([]int{3, 1, 2, 9}) // res == 1
res = pgo.ArrayMin([]float64{3.2, 1.0837, 2.123, 9.87}) // res == 1.0837
ArrayUnique

returns unique values form []T

res = pgo.ArrayUnique([]int{1, 2, 2, 3, 2, 4, 4}) // []int{1, 2, 3, 4}

res = pgo.ArrayUnique([]string{"foo", "bar", "foo", "bar"}) // []string{"bar", "foo"}

Note: order is not guaranteed

ArrayValues

return all the values of map as a slice of values with corresponding type

res = pgo.ArrayValues(map[string]int{"a": 1, "b": 2, "c": 3}) // []int{1, 2, 3}

res = pgo.ArrayValues(map[int]float64{1: 123.33, 2: 22, 3: 123.33}) // []float64{22, 123.33, 123.33}
ArrayReverse

reverse slice passed as an argument

toReverse := []int{-3, 0, 4, 9, 13}
pgo.ArrayReverse(toReverse) 
fmt.Println(toReverse) // []int{13, 9, 4, 0, -3}
Range

creates an int slice of min to max range

pgo.Range(3, 9) // []int{3, 4, 5, 6, 7, 8, 9}

// If a step value is given, it will be used as the increment between elements in the sequence.
pgo.Range(-3, 7, 5) // []int{-3, 2, 7}
EqualSlices

Compares two slices and returns true if they are equal, false otherwise (any type of slices support)

res, err := pgo.EqualSlices([]int{1, 2, 3}, []int{1, 2, 3}) // true

res, err := pgo.EqualSlices([]string{"foo"}, []string{"bar"}) // false

See more examples in *_test.go files.

Collections
Priority Queue
    // Some items and their priorities.
items := map[string]int{
"banana": 3, "apple": 2, "pear": 4, "peach": 1, "plum": 6,
}

// Create a Priority queue, put the items in it, and
// establish the Priority queue (heap) invariants.
pq := make(pgo.PriorityQueue, len(items))
i := 0
for value, priority := range items {
pq[i] = &pgo.Item{
Value:    value,
Priority: priority,
Index:    i,
}
i++
}
pq.Init()

// Insert a new item and then modify its Priority.
item := &pgo.Item{
Value:    "orange",
Priority: 1,
}
pq.Push(item)
pq.Update(item, item.Value, 5)

item := pq.Pop().(*pgo.Item) // 06:plum
item := pq.Pop().(*pgo.Item) // 05:orange
item := pq.Pop().(*pgo.Item) // 04:pear
item := pq.Pop().(*pgo.Item) // 03:banana
// ... 
Network
IP2Long/Long2Ip
long, _ := pgo.IP2long("176.59.34.117") // 2956665461

ip := pgo.Long2ip(2956665461) // "176.59.34.117"
GetMxrr
isMx, mxs, _ := pgo.GetMxrr("google.com") // e.g.: true, n
Math
Rand
rand := pgo.Rand(1, 100)
Crypto
Md5
pgo.Md5("abc123") // e99a18c428cb38d5f260853678922e03
Sha1
pgo.Sha1("abc123") // 6367c48dd193d56ea7b0baad25b19455e529f5ee
Sha2
pgo.Sha2("abc123") // 6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090
HashFile
hex, err := pgo.HashFile("sha1", "example.txt") // 6367c48dd193d56ea7b0baad25b19455e529f5ee
HashHmac
hmac := HashHmac("foo bar baz", "secret", sha256.New) // 9efc4f86917b454deae37c869521f88dee79305303fa2283df0b480e3cc8104c
IsValidMac
IsValidMac("foo bar baz", hmac, "secret", sha256.New) // true/false

Supporters gratitude:

JetBrains logo

Documentation

Index

Constants

View Source
const (
	DivideMicroseconds = 1e3
	DivideMilliseconds = 1e6
)
View Source
const (
	FileAppend = os.O_APPEND
)

FileAppend const mapping php -> go

Variables

This section is empty.

Functions

func ArrayChunk

func ArrayChunk[T comparable](array []T, size int) [][]T

ArrayChunk split an array into chunks

func ArrayCombine

func ArrayCombine[K, V comparable](keys []K, values []V) map[K]V

ArrayCombine creates an array by using one array for keys and another for its values returns map[key]value if both slices are equal and nil otherwise

func ArrayCountValues

func ArrayCountValues[T comparable](array []T) map[T]int

ArrayCountValues counts all the values of an array/slice

func ArrayDiff

func ArrayDiff(arrays ...interface{}) []interface{}

ArrayDiff compares array1 against one or more other arrays returns the values in array1 that are not present in any of the other arrays

func ArrayFilter

func ArrayFilter(array interface{}, callback interface{}) []interface{}

ArrayFilter filters elements of an array using a callback function

func ArrayIntersect

func ArrayIntersect(arrays ...interface{}) []interface{}

ArrayIntersect computes the intersection of arrays

func ArrayMap

func ArrayMap(array interface{}, callback interface{}) []interface{}

ArrayMap applies the callback to the elements of the given arrays

func ArrayMax added in v1.0.1

func ArrayMax[T constraints.IntFloat](a []T) T

ArrayMax finds maximum value from []T

func ArrayMin added in v1.0.1

func ArrayMin[T constraints.IntFloat](a []T) T

ArrayMin finds minimum value from []T

func ArrayReverse added in v1.0.4

func ArrayReverse[V comparable](s []V)

ArrayReverse reverse slice passed as an argument

func ArraySum

func ArraySum[T constraints.IntFloat](array []T) (T, error)

ArraySum calculate the sum of values in an array

func ArrayUdiff added in v0.8.2

func ArrayUdiff(uf func(interface{}, interface{}) int, arrays ...interface{}) []interface{}

ArrayUdiff computes the difference of arrays by using a callback function for data comparison

func ArrayUnique added in v1.0.2

func ArrayUnique[T comparable](a []T) []T

ArrayUnique returns unique values form []T

func ArrayValues added in v1.0.3

func ArrayValues[K, V comparable](a map[K]V) []V

ArrayValues Return all the values of map as a slice of values with corresponding type

func ConcatFast added in v1.0.5

func ConcatFast(s ...string) string

ConcatFast concatenates strings faster than strings.Builder (see benchmarks)

func Date

func Date(args ...interface{}) string

Date returns formatted output of system data/time 1st argument formatted string e.g.: Y-m-d H:i:s 2nd argument int64 unix timestamp

func EqualSlices added in v0.8.4

func EqualSlices[T comparable](a, b []T) bool

EqualSlices compares two slices and returns true if they are equal, false otherwise in case of passing wrong (non-slice) arguments error will be returned

func FileExists

func FileExists(fileName string) bool

FileExists checks wether file or catalog exists or not returning true or false respectfully

func FileGetContents

func FileGetContents(path string, args ...interface{}) (string, error)

FileGetContents reads files, http requests streams path name of a file or domain from where to read data flags[0] - offset flags[1] - maxLen

func FilePutContents

func FilePutContents(fileName, data string, flags ...interface{}) (int, error)

FilePutContents write files with offset/limit fileName name of file to where put data flags[0] - flags how to put this data FileAppend | LockEx

func GetMxrr

func GetMxrr(domain string) (isMx bool, mxs []*net.MX, err error)

GetMxrr Get MX records corresponding to a given Internet host name Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred

func HTTPBuildQuery

func HTTPBuildQuery(pairs map[string]interface{}) string

HTTPBuildQuery Generates a URL-encoded query string from the associative map

func HashFile

func HashFile(algo, fileName string) (string, error)

HashFile hashs file fileName by calculating hash md5/sha1/sha2 based on it's content

func HashHmac added in v0.8.2

func HashHmac(message, secret string, hashAlgo func() hash.Hash) string

HashHmac generates new HMAC based hash returning relevant string

func IP2long

func IP2long(ipAddr string) (uint32, error)

IP2long converts a string containing an (IPv4) Internet Protocol dotted address into a long integer

func InArray

func InArray[T comparable](needle T, haystack []T) bool

InArray checks if a value exists in an array

func IsDir

func IsDir(fileName string) bool

IsDir tells whether the filename is a directory

func IsFile

func IsFile(fileName string) bool

IsFile tells whether the filename is a regular file

func IsLink(fileName string) bool

IsLink tells whether the filename is a symbolic link

func IsValidMac added in v0.8.2

func IsValidMac(message, messageMAC, key string, hashAlgo func() hash.Hash) bool

IsValidMac validates HMAC based hash returning true if it is valid or false otherwise

func Long2ip

func Long2ip(ipLong uint32) string

Long2ip converts an long integer address into a string in (IPv4) Internet standard dotted format

func Md5

func Md5(s string) string

Md5 returns simple md5 in hex generated from string s

func Rand

func Rand(min, max int64) int64

Rand returns a pseudo-random integer between min and max based on unix-nano time seed !! for random numbers suitable for security-sensitive work, use the crypto/rand package instead

func Range

func Range(min, max int, step ...int) []int

Range creates int slice of min to max range If a step value is given, it will be used as the increment between elements in the sequence. step should be given as a positive number. If not specified, step will default to 1.

func Serialize

func Serialize(val interface{}) (string, error)

Serialize encodes Go code entities to string for e.g.: later storage

func Sha1

func Sha1(s string) string

Sha1 returns simple sha1 in hex generated from string s

func Sha2

func Sha2(s string) string

Sha2 returns simple sha1 in hex generated from string s

func StrIReplace

func StrIReplace(args ...interface{}) (string, error)

StrIReplace replaces all occurrences of the search case-insensitive string|slice with the replacement string If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject.

func StrReplace

func StrReplace(args ...interface{}) (string, error)

StrReplace replaces all occurrences of the search string|slice with the replacement string If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject.

func UnixMicro

func UnixMicro() int64

UnixMicro microseconds since unix epoch

func UnixMilli

func UnixMilli() int64

UnixMilli milliseconds since unix epoch

func Unserialize

func Unserialize(val string, v interface{}) error

Unserialize decodes string back into Go code representation

Types

type Context

type Context struct {
	Headers           map[string]string
	RequestMethod     string
	Req               *http.Request
	UploadMaxFileSize int64
}

Context is the opts for http/net requests

func NewContext

func NewContext() *Context

NewContext returns a new Context with preset default headers and request method

func (*Context) MoveUploadedFile

func (c *Context) MoveUploadedFile(fieldName, destination string) bool

MoveUploadedFile uploads file from fieldName to destination path

type Item

type Item struct {
	Value    string // The Value of the item; arbitrary.
	Priority int    // The Priority of the item in the queue.
	// The Index is needed by update and is maintained by the heap.Interface methods.
	Index int // The Index of the item in the heap.
}

An Item is something we manage in a Priority queue.

type PriorityQueue

type PriorityQueue []*Item

A PriorityQueue implements heap.Interface and holds Items.

func (*PriorityQueue) Init

func (pq *PriorityQueue) Init()

func (PriorityQueue) Len

func (pq PriorityQueue) Len() int

func (PriorityQueue) Less

func (pq PriorityQueue) Less(i, j int) bool

func (*PriorityQueue) Pop

func (pq *PriorityQueue) Pop() interface{}

func (*PriorityQueue) Push

func (pq *PriorityQueue) Push(x interface{})

func (PriorityQueue) Swap

func (pq PriorityQueue) Swap(i, j int)

func (*PriorityQueue) Update

func (pq *PriorityQueue) Update(item *Item, value string, priority int)

Update modifies the Priority and Value of an Item in the queue.

type Time

type Time time.Time

func (Time) Microseconds

func (t Time) Microseconds() int64

Microseconds from time.Time Go type

func (Time) Milliseconds

func (t Time) Milliseconds() int64

Milliseconds from time.Time Go type

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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