Documentation
¶
Index ¶
- func ConvertPascalToSnakeWithExtraKey(input map[string]interface{}, extraKeyMappings map[string]string) map[string]interface{}
- func ConvertToJSONB(oldData, newData interface{}) (JSONB, JSONB, error)
- func DecodeBase64(base64Str string) ([]byte, error)
- func DecodeTokenHelper(tokenString string, jwtSecret string) (jwt.MapClaims, error)
- func ExtractImageTypeFromBase64(dataURI string) (string, 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 MarshalJSONB(data JSONB) ([]byte, error)
- func MarshalJSONBA(data JSONBA) ([]byte, error)
- func ParseCustomDate(dateStr, layout string) time.Time
- func ParseISO8601Date(dateStr string) time.Time
- func ParseRFC3339Date(dateStr string) time.Time
- func ReadJSONB(jsonData []byte, target interface{}) error
- 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
- func UnmarshalJSON(data interface{}, target interface{}) error
- type JSONB
- type JSONBA
- 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 DecodeBase64 ¶ added in v1.0.1
DecodeBase64 decodes a base64 string into binary data.
This function takes a base64 encoded string as input and decodes it into its binary representation. It returns the decoded binary data and any error encountered during the decoding process.
Parameters:
- base64Str: string - The base64 encoded string to decode.
Returns:
- []byte: The decoded binary data.
- error: An error if the decoding process fails.
Example: You can use DecodeBase64 to decode a base64 string like this:
base64Str := "SGVsbG8gV29ybGQ=" data, err := DecodeBase64(base64Str) if err != nil { fmt.Println("Error:", err) return }
This will decode the base64 string into binary data.
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 ExtractImageTypeFromBase64 ¶ added in v1.0.1
ExtractImageTypeFromBase64 extracts the image type from a base64 encoded data URI.
This function takes a data URI string as input, which should be in the format "data:image/type;base64,...", and extracts the image type from it. It returns the extracted image type and any error encountered during the extraction process.
Parameters:
- dataURI: string - The data URI string from which to extract the image type.
Returns:
- string: The extracted image type (e.g., "jpeg", "png").
- error: An error if the data URI format is invalid or if the extraction process fails.
Example: Suppose you have a data URI string representing a JPEG image like this:
dataURI := "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QA6RXhpZgAATU0AKgAAAAgAAQA" imageType, err := ExtractImageTypeFromBase64(dataURI) if err != nil { fmt.Println("Error:", err) return }
This will extract the image type "jpeg" from the data URI.
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 MarshalJSONB ¶ added in v1.0.1
MarshalJSONB marshals a JSONB instance into JSON format.
This function takes a JSONB instance as input and marshals it into JSON format. It returns the JSON representation of the input data and any error encountered during the marshaling process.
Parameters:
- data: JSONB - The JSONB instance to marshal into JSON format.
Returns:
- []byte: The JSON representation of the input JSONB instance.
- error: An error if the marshaling process fails.
Example: Suppose you have a JSONB instance named 'jsonData' representing some data. You can marshal it into JSON format like this:
jsonData := JSONB{"name": "John", "age": 30} jsonBytes, err := MarshalJSONB(jsonData) if err != nil { fmt.Println("Error:", err) return }
This will marshal the 'jsonData' into a byte slice containing the JSON representation.
func MarshalJSONBA ¶ added in v1.0.3
MarshalJSONBA marshals the provided JSONBA slice into JSON format.
This function takes a JSONBA slice, which is essentially a slice of map[string]interface{}, and marshals it into JSON format using the encoding/json package.
Parameters:
- data: JSONBA - The JSONBA slice to be marshaled.
Returns:
- []byte: The JSON representation of the provided JSONBA slice.
- error: An error if the marshaling process fails.
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 ReadJSONB ¶ added in v1.0.1
ReadJSONB reads JSON data into the target interface.
This function unmarshals the JSON data contained in the 'jsonData' byte slice into the provided 'target' interface{}. The 'target' must be a pointer to the type into which the JSON data will be unmarshaled. If the unmarshaling process encounters an error, it returns that error. Otherwise, it returns nil.
Parameters:
- jsonData: []byte - The JSON data to be unmarshaled.
- target: interface{} - A pointer to the type into which the JSON data will be unmarshaled.
Returns:
- error: An error if the unmarshaling process fails. Otherwise, returns nil.
Example: Assuming you have JSON data in a byte slice named 'jsonData' and a struct named 'User', you can use ReadJSONB as follows:
var user User err := ReadJSONB(jsonData, &user) if err != nil { fmt.Println("Error:", err) return }
This will unmarshal the JSON data in 'jsonData' into the 'user' struct.
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: "john@example.com"} personMap, err := StructToMap(person)
if err != nil { fmt.Println("Error:", err) return }
The 'personMap' will contain:
map[string]interface{}{ "Name": "John", "Age": 30, "email": "john@example.com", }
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)
func UnmarshalJSON ¶ added in v1.0.1
func UnmarshalJSON(data interface{}, target interface{}) error
UnmarshalJSON unmarshals JSON data into the target interface{}.
This function takes JSON data as input and unmarshals it into the provided target interface{}. If the input data is already a []byte, it directly unmarshals it; otherwise, it marshals the data into []byte first. It returns any error encountered during the unmarshaling process.
Parameters:
- data: interface{} - The JSON data to unmarshal. It can be either a []byte or any other data type that can be marshaled into []byte.
- target: interface{} - A pointer to the type into which the JSON data will be unmarshaled.
Returns:
- error: An error if the unmarshaling process fails.
Example: Suppose you have JSON data in a byte slice named 'jsonData' and a struct named 'User', you can use UnmarshalJSON like this:
var user User err := UnmarshalJSON(jsonData, &user) if err != nil { fmt.Println("Error:", err) return }
This will unmarshal the JSON data in 'jsonData' into the 'user' struct.
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 NewJSONB ¶ added in v1.0.1
NewJSONB creates a new JSONB instance from the provided data.
This function marshals the input 'data' into JSON format and then unmarshals it into a map[string]interface{}. It returns the created JSONB instance and any error encountered during the process.
Parameters:
- data: interface{} - The data to be converted into JSONB. It can be any data type.
Returns:
- JSONB: The created JSONB instance, which is essentially a map[string]interface{}.
- error: An error if the marshaling or unmarshaling process fails.
Example: Suppose you have some data in a struct named 'Person'. You can create a JSONB instance from this data as follows:
person := Person{Name: "John", Age: 30} jsonb, err := NewJSONB(person) if err != nil { fmt.Println("Error:", err) return }
This will convert the 'person' struct into a JSONB instance.
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.
type JSONBA ¶ added in v1.0.3
type JSONBA []map[string]interface{}
func NewJSONBA ¶ added in v1.0.3
NewJSONBA creates a new JSONBA instance from the provided data.
This function marshals the input 'data' into JSON format and then unmarshals it into a slice of map[string]interface{}. It returns the created JSONBA instance and any error encountered during the process.
Parameters:
- data: interface{} - The data to be converted into JSONBA. It can be any data type.
Returns:
- JSONBA: The created JSONBA instance, which is essentially a slice of map[string]interface{}.
- error: An error if the marshaling or unmarshaling process fails.
func (*JSONBA) Scan ¶ added in v1.0.3
Scan populates the JSOBA value from a database driver.Value.
This method takes a database driver.Value and populates the JSOBA 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 JSOBA 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 (JSONBA) Value ¶ added in v1.0.3
Value converts the JSOBA value into a driver.Value for database storage.
This method converts the JSOBA 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 JSOBA 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 JSOBA value into a string.
- Any errors during the conversion process will be returned as an error.