util

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2024 License: CC0-1.0 Imports: 33 Imported by: 0

README

util

Utility package

List of utility

  • Value lookup
  • Value matcher
  • UID Generator
  • ImgProxy URL Generator

Usage

Value lookup & matcher
package main

import (
    "fmt"

	"github.com/diki-haryadi/govega/util"
)

func main() {
	obj := map[string]interface{}{
		"result": map[string]interface{}{
			"name": "SiCepat",
		},
	}

    if util.FieldExist("result.name", obj) {
        fmt.Println("OK")
    }

	name, ok := util.Lookup("result.name", obj)
    if name == "SiCepat" {
        fmt.Println("OK")
    }

    if util.Match("result.name", obj, "SiCepat") {
        fmt.Println("OK")
    }

}
UID Generator
package main

import (
    "fmt"

	"github.com/diki-haryadi/govega/util"
)

func main() {
    var id int64
	id = GenerateRandUID()
    id = GenerateSeqUID()

    uid := NewUIDRandomNum()
    id = uid.Generate()

    uid = NewUIDSequenceNum()
    id = uid.Generate()

    fmt.Println(EncodeUID(id))

}
Snowflake Generator
package main

import (
    "fmt"
    "github.com/diki-haryadi/govega/util"
)

func main() {
	pod, err := NewPOD(&SnowflakeOpts{
		Epoch: 1626670674000, //Set in config
		POD:   1, //Set in config
	})
	if err != nil {
		//Handler error should be fatal or else
	}

	//Generate POD id
	id := pod.Generate()
	
	fmt.Printf("Int64    : %#v", id.Int64()) //31677837479936
	fmt.Printf("String   : %#v", id.String()) //"31677837479936"
	fmt.Printf("Base2    : %#v", id.Base2()) //"111001100111110010010010000000001000000000000"
	fmt.Printf("Base32   : %#v", id.Base32()) //"h36jryryy"
	fmt.Printf("Base36   : %#v", id.Base36()) //"b88lijda8"
	fmt.Printf("Base58   : %#v", id.Base58()) //"fm892iv3"
	fmt.Printf("Base64   : %#v", id.Base64()) //"MzE2Nzc4Mzc0Nzk5MzY="
	fmt.Printf("Bytes    : %#v", id.Bytes()) //[]byte{0x33, 0x31, 0x36, 0x37, 0x37, 0x38, 0x33, 0x37, 0x34, 0x37, 0x39, 0x39, 0x33, 0x36}
	fmt.Printf("IntBytes : %#v", id.IntBytes()) //[8]uint8{0x0, 0x0, 0x1c, 0xcf, 0x92, 0x40, 0x10, 0x0}
}
ImgProxy URL Generator
package main

import (
    "fmt"

	"github.com/diki-haryadi/govega/util"
)

func main() {
	img := NewImageProxy("http://localhost:8080", "https://sicepatresi.s3.amazonaws.com/0016100/001610004980.jpg", "testkey12345", "testkey12345")
	url, err := img.GetURL()
	if err != nil {
		panic(err) 
	}
	fmt.Println(url) //http://localhost:8080/oOXB13_3e8ZR1PTQQLcpI6mHACY7qgvf7GjzypnQOqs/rs:fit:1024:768:0/g:no/aHR0cHM6Ly9zaWNlcGF0cmVzaS5zMy5hbWF6b25hd3MuY29tLzAwMTYxMDAvMDAxNjEwMDA0OTgwLmpwZw.jpg
}

Documentation

Index

Constants

View Source
const (
	//strict equal
	SE = "=="
	EQ = "="
	GT = ">"
	GE = ">="
	LT = "<"
	LE = "<="
	//regex
	RE = "~"
	NE = "!="
	SN = "!=="
	IN = "[]"
	EM = "{}"
)

Variables

View Source
var (
	ErrPodIDExhausted       = errors.New("all available pod id has been acquired")
	ErrMachineIPUnavailable = errors.New("unable to determine machine ip address")
)
View Source
var (
	// Epoch is set to the twitter snowflake epoch of Nov 04 2010 01:42:54 UTC in milliseconds
	// You may customize this to set a different epoch for your application.
	Epoch int64 = 1288834974657 //Default Epoch Time

	// PODBits holds the number of bits to use for Node
	// Remember, you have a total 22 bits to share between Node/Step
	PODBits uint8 = 10

	// StepBits holds the number of bits to use for Step
	// Remember, you have a total 22 bits to share between POD/Step
	StepBits uint8 = 12
)
View Source
var ErrInvalidBase32 = errors.New("invalid base32")

ErrInvalidBase32 is returned by ParseBase32 when given an invalid []byte

View Source
var ErrInvalidBase58 = errors.New("invalid base58")

ErrInvalidBase58 is returned by ParseBase58 when given an invalid []byte

Functions

func Assert

func Assert(name string, context interface{}, value interface{}, op string) bool

func Beautify

func Beautify(data interface{}) string

func CalculateUID

func CalculateUID(node, sequence int64) int64

func CompareValue

func CompareValue(src, dst interface{}, op string) (bool, error)

func Decode

func Decode(input, output interface{}) error

func DecodeJSON

func DecodeJSON(input, output interface{}) error

func DecodeString

func DecodeString(str string) (interface{}, error)

func DecodeTag

func DecodeTag(input, output interface{}, tag string) error

func DenormalizeMSISDN

func DenormalizeMSISDN(msisdn string, format MSISDNFormat) (string, error)

func EncodeUID

func EncodeUID(uid int64) string

func EpochToTime

func EpochToTime(epoch int64) time.Time

func FieldExist

func FieldExist(name string, val interface{}) bool

func FindFieldByTag

func FindFieldByTag(obj interface{}, tag, key string) (string, error)

func FindFieldTypeByTag

func FindFieldTypeByTag(obj interface{}, tag, key string) (reflect.Type, error)

func FromTimeHookFunc

func FromTimeHookFunc() mapstructure.DecodeHookFunc

func GenerateRandNodeUID

func GenerateRandNodeUID() int64

GenerateRandNodeUID generate UID from random NodeID and random sequence number

func GenerateRandUID

func GenerateRandUID() int64

GenerateRandUID generate UID with NodeID from network interface and random sequence number

func GenerateSeqUID

func GenerateSeqUID() int64

GenerateSeqUID generate UID with NodeID from network interface and incremental sequence number

func GetClientIPAddress

func GetClientIPAddress(r *http.Request) string

func GetListenPort

func GetListenPort(hport string) string

applications need some way to access the infrastucture TODO: this method will work only after grace.Serve is called.

func GetNodeIDFromMac

func GetNodeIDFromMac() int64

func GetOffset

func GetOffset(page, limit int) int

func GetRandomNodeID

func GetRandomNodeID() int64

func GetRandomNumber

func GetRandomNumber() int64

func GetSequenceNumber

func GetSequenceNumber() int64

func Hash

func Hash(v interface{}) []byte

Hash calculate value hash

func Hash58

func Hash58(v interface{}) string

func Hash64

func Hash64(v interface{}) string

func HashHex

func HashHex(v interface{}) string

func IsMap

func IsMap(obj interface{}) bool

func IsMapStringInterface

func IsMapStringInterface(obj interface{}) bool

func IsNumber

func IsNumber(val interface{}) bool

func IsPointerOfSlice

func IsPointerOfSlice(obj interface{}) bool

func IsPointerOfStruct

func IsPointerOfStruct(obj interface{}) bool

func IsSlice

func IsSlice(obj interface{}) bool

func IsStruct

func IsStruct(obj interface{}) bool

func IsStructOrPointerOf

func IsStructOrPointerOf(obj interface{}) bool

func IsTime

func IsTime(val interface{}) bool

func ListTag

func ListTag(obj interface{}, tag string) ([]string, error)

func Listen

func Listen(hport string) (net.Listener, error)

This method can be used for any TCP Listener, e.g. non HTTP

func Lookup

func Lookup(name string, context ...interface{}) (interface{}, bool)

Lookup lookup value from interface

func Match

func Match(name string, context interface{}, value interface{}) bool

Match check if value is match with given context and path

func NormalizeMSISDN

func NormalizeMSISDN(msisdn string) (string, error)

func Reverse

func Reverse(s interface{})

func Serve

func Serve(hport string, handler http.Handler, gracefulTimeout, readTimeout, writeTimeout time.Duration) error

func SetValue

func SetValue(obj interface{}, key string, value interface{}) error

func StringToDuration

func StringToDuration(s string) time.Duration

func TimeToDateTimezone

func TimeToDateTimezone(setTime time.Time, timeZone string) time.Time

func ToClock

func ToClock(timeData time.Time) string

func ToTimeHookFunc

func ToTimeHookFunc(format string) mapstructure.DecodeHookFunc

Types

type DistributedPodID

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

func NewDistributedPodID

func NewDistributedPodID(ctx context.Context, prefix string, cache cache.Cache,
	lock lock.DLocker) (*DistributedPodID, error)

func (*DistributedPodID) ID

func (d *DistributedPodID) ID() int64

ID return the acquired pod id.

func (*DistributedPodID) Release

func (d *DistributedPodID) Release(ctx context.Context) error

Release acquired pod id from cache.

type ID

type ID int64

An ID is a custom type used for a snowflake ID. This is used so we can attach methods onto the ID.

func ParseBase2

func ParseBase2(id string) (ID, error)

ParseBase2 converts a Base2 string into a snowflake ID

func ParseBase32

func ParseBase32(b []byte) (ID, error)

ParseBase32 parses a base32 []byte into a snowflake ID NOTE: There are many different base32 implementations so careful when doing any interoperation.

func ParseBase36

func ParseBase36(id string) (ID, error)

ParseBase36 converts a Base36 string into a snowflake ID

func ParseBase58

func ParseBase58(b []byte) (ID, error)

ParseBase58 parses a base58 []byte into a snowflake ID

func ParseBase64

func ParseBase64(id string) (ID, error)

ParseBase64 converts a base64 string into a snowflake ID

func ParseBytes

func ParseBytes(id []byte) (ID, error)

ParseBytes converts a byte slice into a snowflake ID

func ParseInt64

func ParseInt64(id int64) ID

ParseInt64 converts an int64 into a snowflake ID

func ParseIntBytes

func ParseIntBytes(id [8]byte) ID

ParseIntBytes converts an array of bytes encoded as big endian integer as a snowflake ID

func ParseString

func ParseString(id string) (ID, error)

ParseString converts a string into a snowflake ID

func (ID) Base2

func (f ID) Base2() string

Base2 returns a string base2 of the snowflake ID

func (ID) Base32

func (f ID) Base32() string

Base32 uses the z-base-32 character set but encodes and decodes similar to base58, allowing it to create an even smaller result string. NOTE: There are many different base32 implementations so becareful when doing any interoperation.

func (ID) Base36

func (f ID) Base36() string

Base36 returns a base36 string of the snowflake ID

func (ID) Base58

func (f ID) Base58() string

Base58 returns a base58 string of the snowflake ID

func (ID) Base64

func (f ID) Base64() string

Base64 returns a base64 string of the snowflake ID

func (ID) Bytes

func (f ID) Bytes() []byte

Bytes returns a byte slice of the snowflake ID

func (ID) Int64

func (f ID) Int64() int64

Int64 returns an int64 of the snowflake ID

func (ID) IntBytes

func (f ID) IntBytes() [8]byte

IntBytes returns an array of bytes of the snowflake ID, encoded as a big endian integer.

func (ID) MarshalJSON

func (f ID) MarshalJSON() ([]byte, error)

MarshalJSON returns a json byte array string of the snowflake ID.

func (ID) Node

func (f ID) Node() int64

Node returns an int64 of the snowflake ID node number DEPRECATED: the below function will be removed in a future release.

func (ID) Step

func (f ID) Step() int64

Step returns an int64 of the snowflake step (or sequence) number DEPRECATED: the below function will be removed in a future release.

func (ID) String

func (f ID) String() string

String returns a string of the snowflake ID

func (ID) Time

func (f ID) Time() int64

Time returns an int64 unix timestamp in milliseconds of the snowflake ID time DEPRECATED: the below function will be removed in a future release.

func (*ID) UnmarshalJSON

func (f *ID) UnmarshalJSON(b []byte) error

UnmarshalJSON converts a json byte array of a snowflake ID into an ID type.

type ImageProxyOpt

type ImageProxyOpt struct {
	URL       string
	Key       string
	Salt      string
	Resize    string
	Width     int
	Height    int
	Gravity   string
	Extension string
	Enlarge   bool
	ProxyURL  string
}

func NewImageProxy

func NewImageProxy(base, url, key, salt string) *ImageProxyOpt

func (*ImageProxyOpt) GetURL

func (i *ImageProxyOpt) GetURL() (string, error)

type JSONSyntaxError

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

A JSONSyntaxError is returned from UnmarshalJSON if an invalid ID is provided.

func (JSONSyntaxError) Error

func (j JSONSyntaxError) Error() string

type MSISDNFormat

type MSISDNFormat string
const (
	MSISDN08     MSISDNFormat = "08"
	MSISDN8      MSISDNFormat = "8"
	MSISDN62Plus MSISDNFormat = "62"
)

type NodeIDGenerator

type NodeIDGenerator func() int64

type POD

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

A POD struct holds the basic information needed for a snowflake generator node

func NewPOD

func NewPOD(o *SnowflakeOpts) (*POD, error)

NewPOD returns a new snowflake pod that can be used to generate snowflake IDs

func (*POD) Generate

func (n *POD) Generate() ID

Generate creates and returns a unique snowflake ID To help guarantee uniqueness - Make sure your system is keeping accurate system time - Make sure you never have multiple PODS running with the same pod ID

type SequenceGenerator

type SequenceGenerator func() int64

type SnowflakeOpts

type SnowflakeOpts struct {
	Epoch int64 `json:"epoch"`
	POD   int64 `json:"pod"`
}

type UID

type UID struct {
	NodeGen NodeIDGenerator
	SeqGen  SequenceGenerator
}

func NewUIDRandomNum

func NewUIDRandomNum() *UID

func NewUIDSequenceNum

func NewUIDSequenceNum() *UID

func (*UID) Generate

func (u *UID) Generate() int64

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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