util

package
v7.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2022 License: Apache-2.0, BSD-2-Clause, BSD-3-Clause, + 1 more Imports: 22 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const BitsPerByte = 8
View Source
const ConstantBackoffDuration = 30 * time.Second

ConstantBackoffDuration is a fallback duration that may be used by an application along with NewConstantBackoff()

View Source
const DefaultFactor = 2.0

DefaultFactor may be used by applications for the factor argument.

View Source
const MSPerNS = int64(1000000)

Variables

This section is empty.

Functions

func AESDecrypt

func AESDecrypt(bytesToDecrypt []byte, aesKey []byte) ([]byte, error)

AESDecrypt takes in a 16, 24, or 32 byte AES key (128, 192, 256 bit encryption respectively) and encrypted text. It returns the resulting decrypted text. In case of error, the text returned is an empty string. AES requires input text to be greater than 12 bytes in length.

func AESEncrypt

func AESEncrypt(bytesToEncrypt []byte, aesKey []byte) ([]byte, error)

AESEncrypt takes in a 16, 24, or 32 byte AES key (128, 192, 256 bit encryption respectively) and plain text. It returns the encrypted text. In case of error, the text returned is an empty string. AES requires input text to be greater than 12 bytes in length.

func BoolPtr

func BoolPtr(b bool) *bool
Example
ptr := BoolPtr(true)
fmt.Println(*ptr)
Output:

true

func BytesLenSplit

func BytesLenSplit(s []byte, n int) [][]byte

BytesLenSplit splits the given byte array into an n-length arrays. If n > len(s), returns a slice with a single []byte containing all of s. If n <= 0, returns an empty slice.

func CIDRIsSubset

func CIDRIsSubset(na *net.IPNet, nb *net.IPNet) bool

CIDRIsSubset returns whether na is a subset (possibly improper) of nb.

func CamelToSnakeCase

func CamelToSnakeCase(s string) string
Example
camel := "camelCase"
fmt.Println(CamelToSnakeCase(camel))
camel = "PascalCase"
fmt.Println(CamelToSnakeCase(camel))
camel = "IPIsAnInitialismForInternetProtocol"
fmt.Println(CamelToSnakeCase(camel))
Output:

camel_case
pascal_case
ipis_an_initialism_for_internet_protocol

func CoalesceCIDRs

func CoalesceCIDRs(cidrs []*net.IPNet, coalesceNumber int, coalesceMaskLen int) []*net.IPNet

CoalesceCIDRs coalesces cidrs into a smaller set of CIDRs, by combining overlapping networks into networks of size coalesceMaskLen, if there are at least coalesceNumber cidrs in the larger mask.

func CoalesceIPs

func CoalesceIPs(ips []net.IP, coalesceNumber int, coalesceMaskLen int) []*net.IPNet

CoalesceIPs combines ips into CIDRs, by combining overlapping networks into networks of size coalesceMaskLen, if there are at least coalesceNumber IPs in the larger mask.

func ContainsStr

func ContainsStr(a []string, x string) bool
Example
arr := []string{"test", "quest"}
fmt.Println(ContainsStr(arr, "test"))
fmt.Println(ContainsStr(arr, "foo"))
Output:

true
false

func ErrsToStrs

func ErrsToStrs(errs []error) []string
Example
errs := []error{
	errors.New("test"),
	errors.New("quest"),
}
strs := ErrsToStrs(errs)
fmt.Println(strs[0])
fmt.Println(strs[1])
Output:

test
quest

func FirstIP

func FirstIP(ipn *net.IPNet) net.IP

FirstIP returns the first IP in the CIDR. For example, The CIDR 192.0.2.0/24 returns 192.0.2.0.

func FloatPtr

func FloatPtr(f float64) *float64
Example
ptr := FloatPtr(5.0)
fmt.Println(*ptr)
Output:

5

func HashInts

func HashInts(ints []int, sortIntsBeforeHashing bool) []byte

HashInts returns a SHA512 hash of ints. If sortIntsBeforeHashing, the ints are sorted before before hashing. Sorting is done in a copy, the input ints slice is not modified.

func IP4InRange

func IP4InRange(ip, ipRange string) (bool, error)

func IP4ToNum

func IP4ToNum(ip string) (uint32, error)

func IPToCIDR

func IPToCIDR(ip net.IP) *net.IPNet

IPToCIDR returns the CIDR containing just the given IP. For IPv6, this means /128, for IPv4, /32.

func Int64Ptr

func Int64Ptr(i int64) *int64
Example
ptr := Int64Ptr(5)
fmt.Println(*ptr)
Output:

5

func IntPtr

func IntPtr(i int) *int
Example
ptr := IntPtr(5)
fmt.Println(*ptr)
Output:

5

func IntSliceToMap

func IntSliceToMap(s []int) map[int]struct{}

IntSliceToMap creates an int set from an array.

Example
ints := []int{1, 2, 3}
fmt.Printf("%+v", IntSliceToMap(ints))
Output:

map[1:{} 2:{} 3:{}]

func InterfacePtr

func InterfacePtr(i interface{}) *interface{}
Example
ptr := InterfacePtr(1 + 2i)
fmt.Println(*ptr)
Output:

(1+2i)

func JoinErrs

func JoinErrs(errs []error) error

func JoinErrsSep

func JoinErrsSep(errs []error, separator string) error
Example
errs := []error{
	errors.New("test"),
	errors.New("quest"),
}

fmt.Println(JoinErrsSep(errs, "\n"))
Output:

test
quest

func JoinErrsStr

func JoinErrsStr(errs []error) string
Example
errs := []error{
	errors.New("test"),
	errors.New("quest"),
}

fmt.Println(JoinErrsStr(errs))
fmt.Println(JoinErrsStr(nil))
Output:

test, quest

func LastIP

func LastIP(ipn *net.IPNet) net.IP

LastIP returns the last IP in the CIDR. For example, The CIDR 192.0.2.0/24 returns 192.0.2.255.

func RangeStr

func RangeStr(ipn *net.IPNet) string

RangeStr returns the hyphenated range of IPs. For example, The CIDR 192.0.2.0/24 returns "192.0.2.0-192.0.2.255".

func RemoveStrDuplicates

func RemoveStrDuplicates(inputStrings []string, seenStrings map[string]struct{}) ([]string, map[string]struct{})

RemoveStrDuplicates removes duplicates from strings, considering a map of already-seen duplicates. Returns the strings which are unique, and not already present in seen; and a map of the unique strings in inputStrings and seenStrings.

This can be used, for example, to remove duplicates from multiple lists of strings, in order, using a shared map of seen strings.

Example
strs := []string{
	"test",
	"quest",
	"foo",
	"test",
	"foo",
	"bar",
}
unDuped, _ := RemoveStrDuplicates(strs, nil)
for _, str := range unDuped {
	fmt.Println(str)
}
Output:

test
quest
foo
bar

func RemoveStrFromArray

func RemoveStrFromArray(strs []string, s string) []string

RemoveStrFromArray removes a specific string from a string slice.

func Stacktrace

func Stacktrace() []byte

Stacktrace is a helper function which returns the current stacktrace. It wraps runtime.Stack, which requires a sufficiently long buffer.

func StrInArray

func StrInArray(strs []string, s string) bool

StrInArray returns whether s is one of the strings in strs.

Example
arr := []string{"test", "quest"}
fmt.Println(StrInArray(arr, "test"))
fmt.Println(StrInArray(arr, "foo"))
Output:

true
false

func StrPtr

func StrPtr(str string) *string
Example
ptr := StrPtr("testquest")
fmt.Println(*ptr)
Output:

testquest

func StripAllWhitespace

func StripAllWhitespace(s string) string

StripAllWhitespace returns s with all whitespace removed, as defined by unicode.IsSpace.

Example
input := "\n\t \vtest\t\v\r\n quest\v\n \t"
fmt.Println(StripAllWhitespace(input))
Output:

testquest

func TimePtr

func TimePtr(t time.Time) *time.Time

func ToNumeric

func ToNumeric(v interface{}) (float64, bool)

ToNumeric returns a float for any numeric type, and false if the interface does not hold a numeric type. This allows converting unknown numeric types (for example, from JSON) in a single line TODO try to parse string stats as numbers?

func UInt64Ptr

func UInt64Ptr(u uint64) *uint64
Example
ptr := UInt64Ptr(5)
fmt.Println(*ptr)
Output:

5

func UIntPtr

func UIntPtr(u uint) *uint
Example
ptr := UIntPtr(5)
fmt.Println(*ptr)
Output:

5

func Uint64Ptr

func Uint64Ptr(u uint64) *uint64
Example
ptr := Uint64Ptr(5)
fmt.Println(*ptr)
Output:

5

func ValidateAESKey

func ValidateAESKey(keyBytes []byte) error

ValidateAESKey takes in a byte slice and tests if it's a valid AES key (16, 24, or 32 bytes)

Types

type Backoff

type Backoff interface {
	BackoffDuration() time.Duration
	Reset()
}

func NewBackoff

func NewBackoff(min time.Duration, max time.Duration, factor float64) (Backoff, error)

func NewConstantBackoff

func NewConstantBackoff(d time.Duration) Backoff

type BodyInterceptor

type BodyInterceptor struct {
	W         http.ResponseWriter
	BodyBytes []byte
}

BodyInterceptor fulfills the Writer interface, but records the body and doesn't actually write. This allows performing operations on the entire body written by a handler, for example, compressing or hashing. To actually write, call `RealWrite()`. Note this means `len(b)` and `nil` are always returned by `Write()`, any real write errors will be returned by `RealWrite()`.

func (*BodyInterceptor) Body

func (i *BodyInterceptor) Body() []byte

Body returns the internal bytes stored by calls to Write.

func (*BodyInterceptor) Header

func (i *BodyInterceptor) Header() http.Header

Header implements http.ResponseWriter. It returns BodyInterceptor's internal ResponseWriter.Header, without modification or tracking.

Example
i := BodyInterceptor{W: httptest.NewRecorder()}
i.W.Header().Add("test", "quest")
fmt.Println(i.Header().Get("test"))
Output:

quest

func (*BodyInterceptor) RealWrite

func (i *BodyInterceptor) RealWrite(b []byte) (int, error)

RealWrite writes BodyInterceptor's internal bytes, which were stored by calls to Write.

func (*BodyInterceptor) Write

func (i *BodyInterceptor) Write(b []byte) (int, error)

Write implements http.ResponseWriter. It writes the given bytes to BodyInterceptor's internal tracking bytes, and does not write them to the internal ResponseWriter. To write the internal bytes, call BodyInterceptor.RealWrite.

func (*BodyInterceptor) WriteHeader

func (i *BodyInterceptor) WriteHeader(rc int)

WriteHeader implements http.ResponseWriter. It does the real write to Interceptor's internal ResponseWriter, without modification or tracking.

type Interceptor

type Interceptor struct {
	W         http.ResponseWriter
	Code      int
	ByteCount int
}

Interceptor implements http.ResponseWriter. It intercepts writes to w, and tracks the HTTP code and the count of bytes written, while still writing to w.

func (*Interceptor) Header

func (i *Interceptor) Header() http.Header

Header implements http.ResponseWriter. It returns Interceptor's internal ResponseWriter.Header, without modification or tracking.

Example
i := Interceptor{W: httptest.NewRecorder()}
i.W.Header().Add("test", "quest")
fmt.Println(i.Header().Get("test"))
Output:

quest

func (*Interceptor) Write

func (i *Interceptor) Write(b []byte) (int, error)

Write implements http.ResponseWriter. It does the real write to Interceptor's internal ResponseWriter, while keeping track of the count of bytes written. It also sets Interceptor's tracked code to 200 if WriteHeader wasn't called (which is what the real http.ResponseWriter will write to the client).

func (*Interceptor) WriteHeader

func (i *Interceptor) WriteHeader(rc int)

WriteHeader implements http.ResponseWriter. It does the real write to Interceptor's internal ResponseWriter, while keeping track of the code.

type JSONIntStr

type JSONIntStr int64

JSONIntStr unmarshals JSON strings or numbers into an int. This is designed to handle backwards-compatibility for old Perl endpoints which accept both. Please do not use this for new endpoints or new APIs, APIs should be well-typed.

func (JSONIntStr) String

func (i JSONIntStr) String() string
Example
var a JSONIntStr = 5
fmt.Println(a)
Output:

5

func (JSONIntStr) ToInt64

func (i JSONIntStr) ToInt64() int64
Example
var a JSONIntStr = 5
fmt.Printf("%d (%T)\n", a, a)
fmt.Printf("%d (%T)\n", a.ToInt64(), a.ToInt64())
Output:

5 (util.JSONIntStr)
5 (int64)

func (*JSONIntStr) UnmarshalJSON

func (i *JSONIntStr) UnmarshalJSON(d []byte) error

type JSONNameOrIDStr

type JSONNameOrIDStr struct {
	Name *string
	ID   *int
}

JSONNameOrIDStr is designed to handle backwards-compatibility for old Perl endpoints which accept both. Please do not use this for new endpoints or new APIs, APIs should be well-typed. NOTE: this differs from JSONIntStr in that this field could be 1 of 3 options:

  1. string representing an integer
  2. string representing a unique name
  3. integer

func (JSONNameOrIDStr) MarshalJSON

func (i JSONNameOrIDStr) MarshalJSON() ([]byte, error)

func (*JSONNameOrIDStr) UnmarshalJSON

func (i *JSONNameOrIDStr) UnmarshalJSON(d []byte) error

Jump to

Keyboard shortcuts

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