Documentation ¶
Overview ¶
Package utils implements general purpose utility
Index ¶
- Variables
- func Decode(src io.Reader, dest interface{}) error
- func Encode(src interface{}, dest io.Writer) error
- func GetEnv(key string, defaultVal string) string
- func GetEnvAsSlice(name string, defaultVal []string, sep string) []string
- func GetEnvBool(key string, defaultVal bool) bool
- func GetEnvInt(key string, defaultVal int) int
- func GetEnvMust(key string) string
- func GetHash(val string) string
- func GetHostName() string
- func IsASCII(s string) bool
- func IsUTF8(s string) bool
- func JSONTransformer(src interface{}, dest interface{}) error
- func Prepend[T any](a []T, b T) []T
- func StrictJSONTransformer(src interface{}, dest interface{}) error
- type CustomJSONTagHandler
- type Message
- type Payload
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var BodyJSON = NewCustomJSONTagHandler("body")
BodyJSON is a CustomJSONTagHandler instance with the custom tag "body".
var HeaderJSON = NewCustomJSONTagHandler("header")
HeaderJSON is a CustomJSONTagHandler instance with the custom tag "header".
Functions ¶
func Decode ¶
Decode decodes data from the source reader using gob decoding and stores it in the destination interface.
func Encode ¶
Encode encodes the source interface and writes it to the destination writer using gob encoding.
func GetEnv ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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 ¶
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 ¶
NewMessage creates a new Message instance with the specified entity and event. It initializes the Contains slice and Payload map.
func (*Message) AddPayload ¶
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.