Documentation ¶
Index ¶
- func ConvertPascalToSnakeWithExtraKey(input map[string]interface{}, extraKeyMappings map[string]string) map[string]interface{}
- func ConvertToJSONB(oldData, newData interface{}) (JSONB, JSONB, error)
- func DecodeTokenHelper(tokenString string, jwtSecret string) (jwt.MapClaims, error)
- func FloatToString(num float64) string
- func FormatUnixTime(unixTime int64, layout string) string
- func GenerateDynamicJWTWithClaimsHelper(tokenClaims TokenClaims, additionalClaims map[string]interface{}, ...) (string, string, error)
- func GenerateNewJwtTokenHelper(claims jwt.Claims, secretKey []byte) (string, error)
- func IntContains(slice []int, element int) bool
- func IntToString(num int) string
- func IsSlice(v interface{}) bool
- func JoinInts(ints []int, sep string) string
- func ParseCustomDate(dateStr, layout string) time.Time
- func ParseISO8601Date(dateStr string) time.Time
- func ParseRFC3339Date(dateStr string) time.Time
- func SplitString(input, delimiter string) []string
- func StringContains(s []string, e string) bool
- func StringToBool(str string) (bool, error)
- func StringToFloat(str string) (float64, error)
- func StringToInt(str string) (int, error)
- func StructToMap(data interface{}) (map[string]interface{}, error)
- func ToLowerCase(text string) string
- func TrimSpaces(str string) string
- type JSONB
- type TokenClaims
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 ¶
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 ¶
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 ¶
Float to String Conversion Example usage: floatStr := FloatToString(123.456) fmt.Println("Converted string:", floatStr)
func FormatUnixTime ¶
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 ¶
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 ¶
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 ¶
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 ¶
Join Int Slice to String Example usage: ints := []int{1, 2, 3, 4} joined := JoinInts(ints, ", ") fmt.Println("Joined string:", joined)
func ParseCustomDate ¶
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 ¶
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 ¶
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 ¶
SplitString splits a string into an array of substrings based on a delimiter.
func StringContains ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 TrimSpaces ¶
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 ¶
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 ¶
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.