utils

package
v6.0.2 Latest Latest
Warning

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

Go to latest
Published: May 29, 2024 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package utils implements general purpose utility

Index

Examples

Constants

This section is empty.

Variables

View Source
var BodyJSON = NewCustomJSONTagHandler("body")

BodyJSON is a CustomJSONTagHandler instance with the custom tag "body".

View Source
var HeaderJSON = NewCustomJSONTagHandler("header")

HeaderJSON is a CustomJSONTagHandler instance with the custom tag "header".

Functions

func Decode

func Decode(src io.Reader, dest interface{}) error

Decode decodes data from the source reader using gob decoding and stores it in the destination interface.

func Encode

func Encode(src interface{}, dest io.Writer) error

Encode encodes the source interface and writes it to the destination writer using gob encoding.

func GetEnv

func GetEnv(key string, defaultVal string) string

GetEnv retrieves the value of the environment variable named by the key. If the variable is present in the environment, the value (which may be empty) is returned. Otherwise, the defaultVal is returned.

func GetEnvAsSlice

func GetEnvAsSlice(name string, defaultVal []string, sep string) []string

GetEnvAsSlice retrieves the value of the environment variable named by the key, splits it using the specified separator, and returns it as a slice of strings. If the variable is not present in the environment, the defaultVal is returned.

func GetEnvBool

func GetEnvBool(key string, defaultVal bool) bool

GetEnvBool retrieves the value of the environment variable named by the key and converts it to a boolean. If the value is "1" or "true" (case insensitive), it returns true. Otherwise, it returns false. If the variable is not present in the environment, the defaultVal is returned.

func GetEnvInt

func GetEnvInt(key string, defaultVal int) int

GetEnvInt retrieves the value of the environment variable named by the key and converts it to an integer. If the variable is not present in the environment or the value cannot be converted to an integer, the defaultVal is returned.

func GetEnvMust

func GetEnvMust(key string) string

GetEnvMust retrieves the value of the environment variable named by the key. If the variable is not present in the environment, it panics with a custom error.

func GetHash

func GetHash(val string) string

GetHash computes the SHA-256 hash of the input value and returns it as a base64-encoded string.

func GetHostName

func GetHostName() string

GetHostName retrieves the host name of the machine. If an error occurs during retrieval, "localhost" is returned.

func IsASCII

func IsASCII(s string) bool

IsASCII checks if the provided string contains only ASCII characters.

func IsUTF8

func IsUTF8(s string) bool

IsUTF8 checks if the provided string is a valid UTF-8 encoded string.

func JSONTransformer

func JSONTransformer(src interface{}, dest interface{}) error

JSONTransformer copies fields from src (a map or struct object) to dest (another object). The field mapping is based on keys (if src is a map) or JSON struct tags (if src is a struct). This function first marshals src into a JSON byte slice and then unmarshals it into dest. Returns an error if marshalling or unmarshalling fails.

Example
package main

import (
	"fmt"

	"github.com/sabariramc/goserverbase/v6/utils"
)

func main() {
	a := map[string]any{
		"key1": "value1",
		"key2": 10,
		"key3": false,
		"key4": "abc",
	}
	type sample struct {
		Key1 string
		B    int  `json:"key2"`
		C    bool `json:"key3"`
	}
	b := &sample{}
	err := utils.JSONTransformer(a, b)
	if err != nil {
		//error processing
	}
	fmt.Printf("%+v", b)
}
Output:

&{Key1:value1 B:10 C:false}

func Prepend

func Prepend[T any](a []T, b T) []T

Prepend adds an element to the beginning of a slice.

This function takes a slice of any type and an element of the same type, and returns a new slice with the element prepended.

func StrictJSONTransformer

func StrictJSONTransformer(src interface{}, dest interface{}) error

StrictJSONTransformer copies fields from src (a map or struct object) to dest (another object). It enforces strict field matching, throwing an error if there are keys in src that do not have a corresponding field in dest. This function first encodes src into a JSON byte slice and then decodes it into dest using a decoder that disallows unknown fields. Returns an error if encoding or decoding fails.

Example (Failure)
package main

import (
	"fmt"

	"github.com/sabariramc/goserverbase/v6/utils"
)

func main() {
	a := map[string]any{
		"key1": "value1",
		"key2": 10,
		"key3": false,
		"key4": "fasf",
	}

	type sample struct {
		Key1 string
		B    int  `json:"key2"`
		C    bool `json:"key3"`
	}
	b := &sample{}
	err := utils.StrictJSONTransformer(a, b)
	if err != nil {
		fmt.Print(err)
	}
}
Output:

StrictJSONTransformer: error decoding content: utils_test.sample.ReadObject: found unknown field: key4, error found in #10 byte of ...|lse,"key4":"fasf"}
|..., bigger context ...|{"key1":"value1","key2":10,"key3":false,"key4":"fasf"}
|...
Example (Success)
package main

import (
	"fmt"

	"github.com/sabariramc/goserverbase/v6/utils"
)

func main() {
	a := map[string]any{
		"key1": "value1",
		"key2": 10,
		"key3": false,
	}

	type sample struct {
		Key1 string
		B    int  `json:"key2"`
		C    bool `json:"key3"`
	}
	b := &sample{}
	err := utils.StrictJSONTransformer(a, b)
	if err != nil {
		//err is nil
	}
	fmt.Printf("%+v", b)
}
Output:

&{Key1:value1 B:10 C:false}

Types

type CustomJSONTagHandler

type CustomJSONTagHandler struct {
	jsoniter.API
}

CustomJSONTagHandler is a wrapper around jsoniter.API to handle JSON encoding/decoding with a custom struct tag.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/sabariramc/goserverbase/v6/utils"
)

func main() {
	var tag1Json = utils.NewCustomJSONTagHandler("tag1")
	var tag2Json = utils.NewCustomJSONTagHandler("tag2")

	type CorrelationParam struct {
		CorrelationID string `tag1:"x-correlation-id" tag2:"correlationId"`
		ScenarioID    string `tag1:"x-scenario-id,omitempty" tag2:"scenarioId,omitempty"`
		SessionID     string `tag1:"x-session-id,omitempty" tag2:"sessionId,omitempty"`
		ScenarioName  string `tag1:"x-scenario-name,omitempty" tag2:"scenarioName,omitempty"`
	}

	x := CorrelationParam{}
	tag2Data := map[string]string{
		"correlationId": "xyz",
		"scenarioId":    "ScenarioId",
		"sessionId":     "SessionId",
		"scenarioName":  "ScenarioName",
	}
	data, _ := json.Marshal(tag2Data)
	tag2Json.Unmarshal(data, &x)
	fmt.Println(tag2Data["correlationId"])
	fmt.Println(tag2Data["scenarioId"])
	fmt.Println(tag2Data["sessionId"])
	fmt.Println(tag2Data["scenarioName"])
	encodedData, _ := tag1Json.Marshal(x) //Note: CustomJSON.Marshal will only work on `struct` objects
	newData := map[string]string{}
	json.Unmarshal(encodedData, &newData)
	fmt.Printf("%+v", newData)
}
Output:

xyz
ScenarioId
SessionId
ScenarioName
map[x-correlation-id:xyz x-scenario-id:ScenarioId x-scenario-name:ScenarioName x-session-id:SessionId]

func NewCustomJSONTagHandler

func NewCustomJSONTagHandler(tag string) *CustomJSONTagHandler

NewCustomJSONTagHandler creates a new CustomJSONTagHandler with a custom struct tag. It sets up the JSON configuration to escape HTML, sort map keys, validate JSON raw messages, and use the specified tag key.

type Message

type Message struct {
	Entity   string             `json:"entity"`
	Event    string             `json:"event"`
	Contains []string           `json:"contains"`
	Payload  map[string]Payload `json:"payload"`
}

Message is a generic structure to pass messages between services. It includes an entity, event, a list of contained payload names, and a map of payloads. This structure is not mature yet and may undergo changes.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/sabariramc/goserverbase/v6/utils"
)

func main() {
	message := utils.NewMessage("event", "aws.test")
	message.AddPayload("payment", utils.Payload{
		"entity": map[string]interface{}{
			"id":     "pay_14341234",
			"amount": 123,
		},
	})
	message.AddPayload("bank", utils.Payload{
		"entity": map[string]interface{}{
			"id": "bank_fadsfas",
		},
	})
	message.AddPayload("customer", utils.Payload{
		"entity": map[string]interface{}{
			"id": "cust_fasdfsa",
		},
		"state": map[string]interface{}{
			"fromState": "created",
			"toState":   "updated",
		},
	})
	blob, _ := json.MarshalIndent(message, "", "    ")
	fmt.Println(string(blob))
}
Output:

{
	"entity": "event",
	"event": "aws.test",
	"contains": [
		"payment",
		"bank",
		"customer"
	],
	"payload": {
		"bank": {
			"entity": {
				"id": "bank_fadsfas"
			}
		},
		"customer": {
			"entity": {
				"id": "cust_fasdfsa"
			},
			"state": {
				"fromState": "created",
				"toState": "updated"
			}
		},
		"payment": {
			"entity": {
				"amount": 123,
				"id": "pay_14341234"
			}
		}
	}
}

func NewMessage

func NewMessage(entity string, event string) *Message

NewMessage creates a new Message instance with the specified entity and event. It initializes the Contains slice and Payload map.

func (*Message) AddPayload

func (m *Message) AddPayload(name string, payload Payload) error

AddPayload adds a new payload to the Message. It appends the payload name to the Contains slice and stores the payload in the Payload map. If a payload with the same name already exists, it returns an error.

func (*Message) GetPayload

func (m *Message) GetPayload(name string) (p Payload, err error)

GetPayload retrieves a payload by name from the Message. If the payload is found, it returns the payload and no error. If the payload is not found, it returns an error.

type Payload

type Payload map[string]interface{}

Directories

Path Synopsis
Package httputil implements utility for httpClient with request retry and optional tracing
Package httputil implements utility for httpClient with request retry and optional tracing

Jump to

Keyboard shortcuts

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