goease

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: May 11, 2024 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertPascalToSnakeWithExtraKey

func ConvertPascalToSnakeWithExtraKey(input map[string]interface{}, extraKeyMappings map[string]string) map[string]interface{}

ConvertPascalToSnakeWithExtraKey converts keys in a map from PascalCase to snake_case. It also checks for additional key mappings defined in configs.KEY_CONVERT_MAPPING and uses those mappings if available.

Parameters:

input: A map[string]interface{} representing the input data with keys possibly in PascalCase.

Returns:

A map[string]interface{} with keys converted to snake_case. If a key is found in
configs.KEY_CONVERT_MAPPING, it will be replaced with the corresponding value. If not,
the key will be converted to snake_case.

func ConvertToJSONB

func ConvertToJSONB(oldData, newData interface{}) (JSONB, JSONB, error)

ConvertToJSONB converts two input data structures into JSONB types.

This function takes two input interfaces representing data structures and converts them into JSONB types, which are custom types typically used to represent JSON data in databases that support JSONB storage.

Parameters:

  • oldData: interface{} - The old data structure to be converted into a JSONB type.
  • newData: interface{} - The new data structure to be converted into a JSONB type.

Returns:

  • JSONB: A JSONB representation of the old data structure.
  • JSONB: A JSONB representation of the new data structure.
  • error: An error if there's any issue during the conversion process.

Usage Example: Suppose you have two structs named 'OldData' and 'NewData' like this:

type OldData struct {
    Name string
    Age  int
}

type NewData struct {
    Name string
    Age  int
    City string
}

You can convert instances of 'OldData' and 'NewData' into JSONB types like this: oldData := OldData{Name: "John", Age: 30} newData := NewData{Name: "Jane", Age: 25, City: "New York"} oldJSONB, newJSONB, err := ConvertToJSONB(oldData, newData)

if err != nil {
    fmt.Println("Error:", err)
    return
}

Note:

  • This function internally uses encoding/json package to marshal and unmarshal the data structures into JSONB types.
  • Any errors during the conversion process will be returned as an error.

func DecodeTokenHelper

func DecodeTokenHelper(tokenString string, jwtSecret string) (jwt.MapClaims, error)
DecodeTokenHelper decodes and validates a JWT token string and returns its claims.

This function takes a JWT token as a string and decodes it to extract the claims. It also performs validation of the token to ensure its integrity and authenticity. The validation includes checking the signing method to ensure it matches the expected algorithm.

Parameters: - tokenString: string - The JWT token that needs to be decoded and validated.

Returns: - jwt.MapClaims: A map of claims (key-value pairs) extracted from the token if it is valid. - error: An error message if the token is invalid or if any other error occurs during the decoding process.

Process: 1. The function uses `jwt.Parse` to parse the token string. 2. Inside the parsing function, it checks if the token's signing method matches the expected HMAC signing method.

  • If the signing method is not as expected, it returns an error.

3. If the signing method is correct, it returns the secret key used for signing the token. 4. After parsing, the function checks if the token is valid and if the claims type assertion is successful.

  • If successful, it returns the claims.
  • If not, it returns an error which could be due to an invalid token or a failure in the type assertion of claims.

Error Handling: - The function returns an error if the token signing method is not HMAC. - It also returns an error if the token is not valid or if the claims cannot be asserted as jwt.MapClaims.

Note: - The secret key used for validating the token signature is retrieved from `configs.JWT_SECRET`. - It's important that `configs.JWT_SECRET` is consistent with the secret key used for generating the tokens.

func FloatToString

func FloatToString(num float64) string

Float to String Conversion Example usage: floatStr := FloatToString(123.456) fmt.Println("Converted string:", floatStr)

func FormatUnixTime

func FormatUnixTime(unixTime int64, layout string) string

Format Unix Time to String Example usage: formattedTime := FormatUnixTime(1609459200, "2006-01-02 15:04:05") fmt.Println("Formatted time:", formattedTime)

func GenerateDynamicJWTWithClaimsHelper

func GenerateDynamicJWTWithClaimsHelper(tokenClaims TokenClaims, additionalClaims map[string]interface{}, jwtSecret string) (string, string, error)
GenerateDynamicJWTWithClaimsHelper creates an access token and a refresh token based on the provided claims.

This function takes two arguments: `tokenClaims` which is of type TokenClaims and contains the standard JWT claims like issuer (iss), subject (sub), audience (aud), and the expiration times for both access and refresh tokens. The second argument `additionalClaims` is a map of interface{} which allows adding extra information to the token.

The function performs the following operations: 1. It initializes the claims for the access token using both standard claims from `tokenClaims` and additional claims from `additionalClaims`. 2. It sets the "token_type" for the access token to "access". 3. It calls `GenerateNewJwtTokenHelper` to create the JWT access token. 4. It repeats similar steps for the refresh token, setting its "token_type" to "refresh".

Parameters: - tokenClaims: TokenClaims - Struct containing standard JWT claims like issuer, subject, and audience, as well as expiration times for both tokens. - additionalClaims: map[string]interface{} - Map containing additional claims to be included in the token.

Returns: - string: The generated JWT access token. - string: The generated JWT refresh token. - error: An error message in case of failure in token generation.

Errors: - If `GenerateNewJwtTokenHelper` fails to generate either the access or refresh token, the function returns an error.

Note: - It's crucial to ensure that `GenerateNewJwtTokenHelper` and configs.JWT_SECRET are properly set up as they play a key role in token generation. - The function assumes the `tokenClaims` struct is properly populated, especially the expiration times for both tokens Latest Modified: [Sat, 06 Jan 2024 03:51:24 GMT]

func GenerateNewJwtTokenHelper

func GenerateNewJwtTokenHelper(claims jwt.Claims, secretKey []byte) (string, error)
 GenerateNewJwtTokenHelper creates a new JWT token based on the provided claims and secret key.

 This function is responsible for generating a JWT (JSON Web Token) using the specified claims
 and a secret key. It uses the HMAC SHA256 signing method for token generation. The function is
 mainly used for creating refresh tokens, but it is generic enough to be used for any JWT creation
 where HMAC SHA256 is the appropriate signing method.

 Example Usage:

	claims := jwt.MapClaims{
	    "sub": "1234567890",
	    "name": "John Doe",
	    "admin": true,
	    "iat": time.Now().Unix(),
	}
	secretKey := []byte("your-256-bit-secret")
	token, err := GenerateNewJwtTokenHelper(claims, secretKey)
	if err != nil {
	    fmt.Println("Error generating JWT token:", err)
	} else {
	    fmt.Println("Generated JWT token:", token)
	}

 Parameters:

	claims: A jwt.Claims object containing the claims for the token. These claims are the
	        payload of the token and typically include user details and token metadata.
	secretKey: A byte slice representing the secret key used for signing the token.

 Returns:

	A string representing the generated JWT token if the process is successful.
	An error if there is any issue in token generation, such as an error in signing.

 Note:

	The function currently only supports HMAC SHA256 signing method. If other signing methods
	are required, additional functions or modifications to this function would be necessary.

 Latest Modified: [Sat, 06 Jan 2024 03:51:24 GMT]

func IntContains

func IntContains(slice []int, element int) bool

Check if Int is in Slice Example usage: intSlice := []int{10, 20, 30, 40} intContains := IntContains(intSlice, 20) fmt.Println("Slice contains 20:", intContains)

func IntToString

func IntToString(num int) string

Int to String Conversion Example usage: str := IntToString(123) fmt.Println("Converted string:", str)

func IsSlice

func IsSlice(v interface{}) bool

IsSlice checks if the given value is a slice.

This function takes an input value and checks whether it is a slice or not. It utilizes reflection to determine the kind of the value.

Parameters:

  • v: interface{} - The value to be checked.

Returns:

  • bool: true if the value is a slice, false otherwise.

Usage Example:

var arr []int
result := IsSlice(arr) // result will be true

var str string
result := IsSlice(str) // result will be false

Note:

  • This function is useful for checking whether a value is a slice before performing operations specific to slices.
  • It uses reflection to determine the kind of the value, which may have a performance overhead.

func JoinInts

func JoinInts(ints []int, sep string) string

Join Int Slice to String Example usage: ints := []int{1, 2, 3, 4} joined := JoinInts(ints, ", ") fmt.Println("Joined string:", joined)

func ParseCustomDate

func ParseCustomDate(dateStr, layout string) time.Time

ParseCustomDate parses a date string in a custom format.

Parameters:

  • dateStr: string - The date string to parse.
  • layout: string - The layout to use for parsing.

Returns:

  • time.Time: The parsed time if successful, otherwise a zero time.

func ParseISO8601Date

func ParseISO8601Date(dateStr string) time.Time

ParseISO8601Date parses a date string in ISO8601 format.

Parameters:

  • dateStr: string - The date string to parse.

Returns:

  • time.Time: The parsed time if successful, otherwise a zero time.

func ParseRFC3339Date

func ParseRFC3339Date(dateStr string) time.Time

ParseRFC3339Date parses a date string in RFC3339 format.

Parameters:

  • dateStr: string - The date string to parse.

Returns:

  • time.Time: The parsed time if successful, otherwise a zero time.

func SplitString

func SplitString(input, delimiter string) []string

SplitString splits a string into an array of substrings based on a delimiter.

func StringContains

func StringContains(s []string, e string) bool

Helper function to check if a string is in a slice of strings Check if String is in Slice Example usage: slice := []string{"apple", "banana", "cherry"} contains := StringContains(slice, "banana") fmt.Println("Slice contains 'banana':", contains)

func StringToBool

func StringToBool(str string) (bool, error)

Convert String to Boolean Example usage: b, err := StringToBool("true")

if err != nil {
    fmt.Println("Error converting string to bool:", err)
} else {

    fmt.Println("Converted boolean:", b)
}

func StringToFloat

func StringToFloat(str string) (float64, error)

String to Float Conversion Example usage: f, err := StringToFloat("123.45")

if err != nil {
    fmt.Println("Error converting string to float:", err)
} else {

    fmt.Println("Converted float:", f)
}

func StringToInt

func StringToInt(str string) (int, error)

String to Int Conversion Example usage: num, err := StringToInt("123")

if err != nil {
    fmt.Println("Error converting string to int:", err)
} else {

    fmt.Println("Converted number:", num)
}

func StructToMap

func StructToMap(data interface{}) (map[string]interface{}, error)

StructToMap converts a struct into a map[string]interface{}.

This function takes an input interface{} representing a struct and converts it into a map where the keys are the field names of the struct, and the values are the corresponding field values. It is particularly useful when you need to work with data in a more dynamic or generic way.

Parameters:

  • data: interface{} - The input value that should be a struct. It accepts an interface to be more flexible in what types can be passed.

Returns:

  • map[string]interface{}: A map representation of the struct where field names are the keys and field values are the values.
  • error: An error if the input is not a struct.

Usage Example: Suppose you have a struct named 'Person' like this:

type Person struct {
    Name  string
    Age   int
    Email string `json:"email"`
}

You can convert an instance of 'Person' into a map using StructToMap like this: person := Person{Name: "John", Age: 30, Email: "[email protected]"} personMap, err := StructToMap(person)

if err != nil {
    fmt.Println("Error:", err)
    return
}

The 'personMap' will contain:

map[string]interface{}{
    "Name":  "John",
    "Age":   30,
    "email": "[email protected]",
}

Note:

  • StructToMap supports struct tags to customize the keys in the resulting map. If a JSON tag is available for a field, it will be used as the key. Otherwise, the field name will be used.
  • Only exported (public) fields of the struct can be converted, as unexported (private) fields cannot be accessed.
  • It's important to ensure that the input 'data' is indeed a struct, as non-struct types will result in an error.

func ToLowerCase

func ToLowerCase(text string) string

func TrimSpaces

func TrimSpaces(str string) string

Trim String Spaces Example usage: trimmed := TrimSpaces(" hello world ") fmt.Println("Trimmed string:", trimmed)

Types

type JSONB

type JSONB map[string]interface{}

JSONB represents a JSONB type typically used to store JSON data in databases.

JSONB is a custom type defined as a map[string]interface{}, allowing for flexible representation of JSON data.

Methods:

  • Value(): (JSONB method) Converts the JSONB value into a driver.Value for database storage.
  • Scan(value interface{}): (JSONB method) Populates the JSONB value from a database driver.Value.

Usage Example:

type MyData struct {
    Name string
    Age  int
}

jsonData := JSONB{"data": MyData{Name: "John", Age: 30}}

// Conversion to driver.Value for database storage
dbValue, err := jsonData.Value()

// Populating JSONB from database driver.Value
var retrievedData JSONB
err := retrievedData.Scan(dbValue)

Note:

  • JSONB is typically used to represent JSON data in databases that support JSONB storage.
  • The Value() method is used to convert JSONB into a database-friendly format for storage.
  • The Scan() method is used to populate JSONB from a database driver.Value.

func (*JSONB) Scan

func (j *JSONB) Scan(value interface{}) error

Scan populates the JSONB value from a database driver.Value.

This method takes a database driver.Value and populates the JSONB value with the corresponding data. It's typically used when retrieving JSONB data from databases that support JSONB storage.

Parameters:

  • value: interface{} - The database driver.Value to be scanned into the JSONB value.

Returns:

  • error: An error if there's any issue during the scanning process.

Note:

  • This method expects the database driver.Value to be a byte slice representing JSON data.
  • Any errors during the scanning process will be returned as an error.

func (JSONB) Value

func (j JSONB) Value() (driver.Value, error)

Value converts the JSONB value into a driver.Value for database storage.

This method converts the JSONB value into a string representation before returning it as a driver.Value. It's typically used for storing JSONB data in databases that support JSONB storage.

Returns:

  • driver.Value: A driver.Value representing the JSONB value for database storage.
  • error: An error if there's any issue during the conversion process.

Note:

  • This method internally uses the encoding/json package to marshal the JSONB value into a string.
  • Any errors during the conversion process will be returned as an error.

type TokenClaims

type TokenClaims struct {
	Iss string // Issuer
	Sub string // Subject
	Aud string // Audience
	// minutes
	AccessExp  int64
	RefreshExp int64
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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