help

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2024 License: MIT Imports: 22 Imported by: 22

README

go-helpers

This is a helper library for the GoLang project.

Features

String helpers
Functions Description
ToLower Converts a given string to lower case.
ToUpper Converts a given string to upper case.
ToSentenceCase Converts a given string to sentence case.
ToTitle Converts a given string to title case or Capitalized Each Word.
GenerateRandomString Generates a random string of a specified length using the alphabet characters. It uses the current time as a seed for the random number generator.
GeneratePassword Generates a random password of a specified length using a combination of lowercase letters, uppercase letters, numbers, and special characters.
GenerateUUID Generates a new V7 (random) UUID. The function returns the generated UUID and an error if any.
HashPassword Generates a hashed password from a plain text password using bcrypt. The function returns the hashed password and an error if any.
PasswordIsValid Checks if a given plain text password matches the hashed password. The function returns true if the passwords match, false otherwise.
CheckStringValue Checks if a given string is not empty. The function returns true if the string is not empty, false otherwise.
CheckStringValueToPointer Checks if a given string is not empty and returns a pointer to the string. The function returns a pointer to the string if the string is not empty, nil otherwise.
Translate Translates a given string from source language to target language. The function returns the translated string and an error if any.
IsUUID Checks if the given string is a valid UUID. The function returns true if the string is a valid UUID, false otherwise.
IsEmail Checks if the given string is a valid email. The function returns true if the string is a valid email, false otherwise.
IsNumber Checks if the given string is a valid number. The function returns true if the string is a valid number, false otherwise.
IsPhoneNumberId Checks if the given string is a valid phone number ID. The function returns true if the string is a valid phone number ID, false otherwise.
Number helpers
Functions Description
RoundUpFloat Rounds up the given float64 to the given uint precision. For example, if the input is 12.345 and the precision is 2, this function will return 12.35.
RoundDownFloat Rounds down the given float64 to the given uint precision. For example, if the input is 12.345 and the precision is 2, this function will return 12.34.
RoundFloat Rounds the given float64 to the given uint precision, based on the rounding mode. The rounding mode is determined by the roundingUp parameter.
GenerateRandomNumber Generates a random number within a specified length. The length parameter determines the maximum value of the generated number.
GetMinMaxIntArray Get the minimum and maximum values in an array of int. The function returns the minimum and maximum values as a tuple.
CheckArrayFloat64Nil Checks if the input array of float64 is nil or empty. If not, it returns the input array. If the input array is nil or empty, it returns an empty array.
CheckFloat64Value Checks if the input pointer to a float64 is nil or empty. If not, it returns the value of the input pointer. If the input pointer is nil, it returns 0.0.
Json helpers
Functions Description
SafeJsonMarshal Marshals a given data to json. If the Marshal process is failed, it will return the original Marshal result and the error.
JsonToStruct UnMarshals a json string to a struct. If the UnMarshal process is failed, it will return the original Marshal result and the error.
JsonToString Marshals a struct to json string. If the Marshal process is failed, it will return the original Marshal result and the error.
Net helpers
Functions Description
QueryEscape Escape a string for use in a URL query.
StreamToString Reads the entire contents of an io.Reader and returns it as a string.
StreamToByte Reads the entire contents of an io.Reader and returns it as a byte slice.
GetHTTPRequestJSON Sends an HTTP request with the given method, URL, body, and timeout, and returns the response as a byte slice. The function takes an optional set of headers to include with the request.
GetHTTPRequestSkipVerify Sends an HTTP request with the given method, URL, body, and timeout, and returns the response as a byte slice. The function takes an optional set of headers to include with the request.
NewHttpDecoder Creates a new HttpDecoder, which can be used to decode HTTP requests.
Time helpers
Response mapper
Others
Functions Description
FormatErrorValidator Formats multiple validation error messages. It takes a slice of validator.ValidationErrors and returns a slice of strings, where each string is a formatted error message.
FormatErrorValidatorSingle Formats a single validation error message. It takes a validator.ValidationErrors and returns a formatted error message.
PanicRecover This function is used to recover from a panic. It takes a string as an argument and prints it to the console.

Installation

  go get github.com/adamnasrudin03/go-helpers@latest

Usage

Check in go playground: https://go.dev/play/p/Qidzj-zwSa1

package main

import (
	"fmt"

	help "github.com/adamnasrudin03/go-helpers"
)

func main() {
	fmt.Println(help.ToLower("Lorem ipsum dolor sit amet."))        // output; lorem ipsum dolor sit amet.
	fmt.Println(help.ToUpper("Lorem ipsum dolor sit amet."))        // output; LOREM IPSUM DOLOR SIT AMET.
	fmt.Println(help.ToSentenceCase("LOREM IPSUM DOLOR SIT AMET.")) // output; Lorem ipsum dolor sit amet.
	fmt.Println(help.ToTitle("Lorem ipsum dolor sit amet."))        // output; Lorem Ipsum Dolor Sit Amet.
}

other examples: https://github.com/adamnasrudin03/go-helpers/tree/main/examples

How to Contribute

Make a pull request...

License

Distributed under MIT License, please see license file within the code for more details.

Documentation

Overview

Package help provides utilities for handling HTTP requests.

Index

Constants

View Source
const (
	CharsetAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	CharsetAll      = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()+,-.:;<=>?[]_{}"
)
View Source
const (
	// Format date time
	FormatDateTime            = `2006-01-02 15:04:05`
	FormatDateHourMinutes     = `2006-01-02 15:04`
	FormatDate                = `2006-01-02`
	FormatDateDDMMYYYY        = `02-01-2006`
	FormatLocalTime           = `02-Jan-2006`
	FormatLocalTimeDDsMMsYYYY = `02 Jan 2006`
	FormatDateConcise         = `02-Jan-06`
	FormatDateMonthYear       = `02 January 2006`
	FormatDateMonth           = `02 January`
	FormatTimeMinute          = `15:04`
	FormatTimeMinuteSecond    = `15:04:05`

	// Timezone country
	AsiaJakarta  = `Asia/Jakarta`
	AsiaMakassar = `Asia/Makassar`
	AsiaJayapura = `Asia/Jayapura`

	// indonesia country timezone in table city
	GMT7 = `GMT+7:00`
	GMT8 = `GMT+8:00`
	GMT9 = `GMT+9:00`

	// Month
	January   = `January`
	February  = `February`
	March     = `March`
	April     = `April`
	May       = `May`
	June      = `June`
	July      = `July`
	August    = `August`
	September = `September`
	October   = `October`
	November  = `November`
	December  = `December`
)
View Source
const (
	Auto = "auto"
)

Variables

View Source
var (
	LangID = language.Indonesian.String()
	LangEn = language.English.String()
)
View Source
var (

	// Mapping Timezone ToT imeLocation ...
	MappingTimezoneToTimeLocation = map[string]string{
		GMT7: AsiaJakarta,
		GMT8: AsiaMakassar,
		GMT9: AsiaJayapura,
	}

	// Month English(en) to Indonesian(id)
	MappingMonthEnToId = map[string]string{
		January:   `Januari`,
		February:  `Februari`,
		March:     `Maret`,
		April:     `April`,
		May:       `Mei`,
		June:      `Juni`,
		July:      `Juli`,
		August:    `Agustus`,
		September: `September`,
		October:   `Oktober`,
		November:  `November`,
		December:  `Desember`,
	}
)
View Source
var (
	IsStatusSuccess = map[int]bool{
		http.StatusOK:      true,
		http.StatusCreated: true,
	}
)

Functions

func CheckArrayFloat64Nil

func CheckArrayFloat64Nil(input []float64) []float64

CheckArrayFloat64Nil checks if the input array of float64 is nil or empty. If not, it returns the input array. If the input array is nil or empty, it returns an empty array.

Parameters: - input: An array of float64.

Returns: - An array of float64.

func CheckArrayIntNil

func CheckArrayIntNil(input []int) []int

CheckArrayIntNil checks if the input array of integers is nil or empty. If not, it returns the input array. If the input array is nil or empty, it returns an empty array.

Parameters: - input: An array of integers.

Returns: - An array of integers.

func CheckFloat64Value

func CheckFloat64Value(input *float64) float64

CheckFloat64Value checks if the input pointer to a float64 is nil or empty. If not, it returns the value of the input pointer. If the input pointer is nil, it returns 0.0.

Parameters: - input: A pointer to a float64.

Returns: - A float64.

func CheckIntValue

func CheckIntValue(input *int) int

CheckIntValue checks if the input pointer of integer is nil or empty. If not, it returns the value of the input pointer. If the input pointer is nil or empty, it returns 0.

Parameters: - input: A pointer of integer.

Returns: - An integer.

func CheckStringValue

func CheckStringValue(input *string) string

CheckStringValue returns an empty string if the input pointer to a string is nil, otherwise it returns the value of the input pointer.

Parameters: - input: A pointer to a string.

Returns: - A string.

func CheckStringValueToPointer

func CheckStringValueToPointer(input string) *string

CheckStringValueToPointer returns a pointer to a string or nil if the input string is empty or only contains whitespace.

Parameters: - input: A string.

Returns: - A pointer to a string.

func CheckTimeIsZeroToPointer

func CheckTimeIsZeroToPointer(t time.Time) *time.Time

CheckTimeIsZeroToPointer returns a pointer to a time.Time if the input time is not zero, otherwise it returns nil.

Parameters: - t: A time.Time object.

Returns: - A pointer to a time.Time object.

func CheckTimeIsZeroToString

func CheckTimeIsZeroToString(t time.Time, formatDate string) string

CheckTimeIsZeroToString converts a time.Time object to a string if it is not zero, otherwise it returns an empty string.

Parameters: - t: A time.Time object. - formatDate: The desired format of the output string.

Returns: - A string representation of the time.Time object if it is not zero, otherwise an empty string.

func CheckTimePointerToString

func CheckTimePointerToString(t *time.Time, formatDate string) string

CheckTimePointerToString converts a pointer to a time.Time object to a string, using the specified format. If the pointer is nil, it returns an empty string.

Parameters: - t: A pointer to a time.Time object. - formatDate: The desired format of the output string.

Returns: - A string representation of the time.Time object, formatted according to the specified format. - If the input pointer is nil, an empty string is returned.

func CheckTimePointerValue

func CheckTimePointerValue(t *time.Time) time.Time

CheckTimePointerValue returns the value of a time.Time pointer. If the pointer is nil, it returns the zero value of time.Time.

Parameters: - t: A pointer to a time.Time object.

Returns: - The value of the time.Time object pointed to by the input pointer.

func GeneratePassword

func GeneratePassword(length int) string

GeneratePassword generates a random password of a specified length using a combination of lowercase letters, uppercase letters, numbers, and special characters.

Parameters: - length: The length of the password to be generated.

Returns: - A string of the specified length consisting of random characters.

func GenerateRandomNumber

func GenerateRandomNumber(length int) int

GenerateRandomNumber generates a random number within a specified length. The length parameter determines the maximum value of the generated number.

Parameters: - length: The length of the number range.

Returns: - A randomly generated number within the specified range. see https://adamnasrudin.vercel.app/cheat-sheet/generate-random-number-using-golang

func GenerateRandomString

func GenerateRandomString(length int) string

GenerateRandomString generates a random string of a specified length using the alphabet characters. It uses the current time as a seed for the random number generator.

Parameters: - length: The length of the string to be generated.

Returns: - A string of the specified length consisting of alphabet characters.

func GenerateUUID added in v0.0.3

func GenerateUUID() (uuid.UUID, error)

GenerateUUID generates a new UUID v7

It returns a UUID v7 and an error, if any. see https://adamnasrudin.vercel.app/cheat-sheet/generate-uuid-in-golang

func GetHTTPRequestJSON

func GetHTTPRequestJSON(ctx context.Context, method string, url string, body io.Reader, customTimeOut int, headers ...map[string]string) (res []byte, statusCode int, err error)

GetHTTPRequestJSON sends an HTTP request with the given method, URL, body, and timeout, and returns the response as a byte slice. The function takes an optional set of headers to include with the request.

Parameters: - ctx: The context to use for the request. - method: The HTTP method to use (e.g. "GET", "POST", etc.). - url: The URL to send the request to. - body: The body of the request to send. - customTimeOut: The timeout to use for the request, in seconds. - headers: An optional set of headers to include with the request.

Returns: - res: The response from the server as a byte slice. - statusCode: The HTTP status code of the response. - err: An error if the request fails.

func GetHTTPRequestSkipVerify

func GetHTTPRequestSkipVerify(ctx context.Context, method string, url string, body io.Reader, customTimeOut int, headers ...map[string]string) (res []byte, statusCode int, err error)

GetHTTPRequestSkipVerify sends an HTTP request with the given method, URL, body, and timeout, and returns the response as a byte slice. The function takes an optional set of headers to include with the request.

Skips SSL certificate verification.

Parameters: - ctx: The context to use for the request. - method: The HTTP method to use (e.g. "GET", "POST", etc.). - url: The URL to send the request to. - body: The body of the request to send. - customTimeOut: The timeout to use for the request, in seconds. - headers: An optional set of headers to include with the request.

Returns: - res: The response from the server as a byte slice. - statusCode: The HTTP status code of the response. - err: An error if the request fails.

func GetMinMaxIntArray added in v0.0.3

func GetMinMaxIntArray(params []int) (min int, max int)

GetMinMaxIntArray calculates the minimum and maximum values in an array of Int.

Parameters: - params: An array of Int values.

Returns: - min: The minimum value in the array. - max: The maximum value in the array.

func HashPassword

func HashPassword(password string) (hashed string, err error)

HashPassword generates a hashed password from a plain text password using bcrypt. The function returns the hashed password and an error if any. check https://adamnasrudin.vercel.app/cheat-sheet/hash-validate-password

func IsEmail

func IsEmail(email string) bool

IsEmail checks if the given email is in a valid format.

Parameters: - email: The email address to be validated.

Returns: - A boolean indicating whether the email is valid or not.

func IsNumber

func IsNumber(input string) bool

IsNumber checks if the given string is a valid number.

Parameters: - input: The string to be validated.

Returns: - A boolean indicating whether the string is a valid number or not.

func IsPhoneNumberId added in v0.0.3

func IsPhoneNumberId(input string) bool

IsPhoneNumberId checks if the given string is a valid Indonesian phone number.

Parameters: - input: The string to be validated.

Returns: - A boolean indicating whether the string is a valid phone number or not.

The function first removes any whitespace or dashes from the input string. Then it trims any non-digit characters from the input string, keeping only the digit characters and the "+" character, which is used to indicate the country code. The trimmed string is then matched against a regular expression pattern. If the trimmed string matches the pattern, the function returns true, otherwise it returns false.

func IsUUID

func IsUUID(input string) bool

IsUUID checks if the given string is a valid UUID.

Parameters: - input: The string to be validated.

Returns: - A boolean indicating whether the string is a valid UUID or not.

func JsonToString added in v0.0.3

func JsonToString(data interface{}) (string, error)

JsonToString is a function that marshal a struct to json string.

Parameters: - data: the struct to be marshaled to json.

Returns: - string: the marshaled json string. - error: the error if the Marshal process is failed, otherwise nil.

func JsonToStruct added in v0.0.3

func JsonToStruct(params string, data interface{}) error

JsonToStruct is a function that unmarshal a json string to a struct.

Parameters: - params: the json string to be unmarshaled to the struct. - data: the struct to be unmarshaled to.

Returns: - error: the error if the Unmarshal process is failed, otherwise nil.

func PanicRecover

func PanicRecover(opName string)

func PasswordIsValid added in v0.0.3

func PasswordIsValid(hashPassword, password string) bool

PasswordIsValid checks if a given plain text password matches the hashed password. The function returns true if the passwords match, false otherwise. check https://adamnasrudin.vercel.app/cheat-sheet/hash-validate-password

func QueryEscape

func QueryEscape(s string) string

QueryEscape is a wrapper around the net/url.QueryEscape function. It trims the input string and then encodes it using the URL encoding.

s: the string to be encoded returns: the encoded string

func RoundDownFloat

func RoundDownFloat(input float64, precision uint) float64

RoundDownFloat rounds down the given float64 to the given uint precision.

Rounds down the given float64 to the given uint precision. For example, if the input is 12.345 and the precision is 2, this function will return 12.34.

Parameters: - input: The float64 to be rounded down. - precision: The number of decimal places to round to.

Returns: - The rounded down float64.

check https://adamnasrudin.vercel.app/cheat-sheet/rounding-float-using-golang

func RoundUpFloat

func RoundUpFloat(input float64, precision uint) float64

RoundUpFloat rounds up the given float64 to the given uint precision.

Rounds up the given float64 to the given uint precision. For example, if the input is 12.345 and the precision is 2, this function will return 12.35.

Parameters: - input: The float64 to be rounded up. - precision: The number of decimal places to round to.

Returns: - The rounded up float64.

check https://adamnasrudin.vercel.app/cheat-sheet/rounding-float-using-golang

func SafeJsonMarshal

func SafeJsonMarshal(data interface{}) ([]byte, error)

SafeJsonMarshal is a function that safely marshal a data to json. If the Marshal process is failed, it will return the original Marshal result and the error. This function is useful when you want to ensure that the data is marshaled to json without any errors.

Parameters: - data: the data to be marshaled to json.

Returns: - []byte: the marshaled json data. - error: the error if the Marshal process is failed, otherwise nil.

func StreamToByte

func StreamToByte(stream io.Reader) []byte

StreamToByte converts an io.Reader to a byte slice.

Parameters: - stream: The io.Reader to be converted.

Returns: - A byte slice representation of the io.Reader, or an empty byte slice if the input is nil.

func StreamToString

func StreamToString(stream io.Reader) string

StreamToString converts an io.Reader to a string.

Parameters: - stream: The io.Reader to be converted.

Returns: - A string representation of the io.Reader, or an empty string if the input is nil.

func ToLower

func ToLower(input string) string

ToLower converts a given string to lower case.

Parameters: - input: The string to be converted.

Returns: - The lower case version of the input string..

Example: - HELLO WORLD => hello world

Check https://adamnasrudin.vercel.app/cheat-sheet/change-case-string-in-golang

func ToSentenceCase

func ToSentenceCase(input string) string

ToSentenceCase converts a given string to sentence case.

Parameters: - input: The string to be converted.

Returns: - The sentence case version of the input string.

Example: - hello world => Hello World

Check https://adamnasrudin.vercel.app/cheat-sheet/change-case-string-in-golang

func ToTitle

func ToTitle(input string) string

ToTitle converts a given string to title case.

Parameters: - input: The string to be converted.

Returns: - The title case version of the input string.

Example: - hello world => Hello World

Check https://adamnasrudin.vercel.app/cheat-sheet/change-case-string-in-golang

func ToUpper

func ToUpper(input string) string

ToUpper converts a given string to upper case. Parameters: - input: The string to be converted.

Returns: - The upper case version of the input string.

Example: - hello world => HELLO WORLD

Check https://adamnasrudin.vercel.app/cheat-sheet/change-case-string-in-golang

func Translate

func Translate(source, sourceLang, targetLang string) (string, error)

Translate text from source language to target language https://cloud.google.com/translate/automl/docs/reference/rest/v3/projects.locations/translateText

Types

type HttpDecoder added in v0.0.8

type HttpDecoder interface {
	// SetMaxSize sets the maximum size of the request body.
	// The parameter limit is the maximum size in bytes.
	SetMaxSize(limit int64)

	// SetTagName sets the tag name for conform parsing.
	// The parameter tag is the name of the tag.
	SetTagName(tag string)

	// Body decodes the request body into the given interface.
	// It supports JSON and form data.
	Body(r *http.Request, i interface{}, fns ...OptionDecoder) error

	// Query decodes the query parameters into the given interface.
	Query(r *http.Request, i interface{}, fns ...OptionDecoder) error
}

HttpDecoder is the interface that decodes HTTP requests.

func NewHttpDecoder added in v0.0.8

func NewHttpDecoder() HttpDecoder

NewHttpDecoder creates a new HttpDecoder with default settings.

type OptionDecoder added in v0.0.8

type OptionDecoder struct {
	// Func is the function used to decode custom types.
	Func form.DecodeCustomTypeFunc
	// Types is the list of types that can be decoded.
	Types []interface{}
}

OptionDecoder is used to configure the decoder for custom types.

type OptionTimeUTC7 added in v0.0.3

type OptionTimeUTC7 func(*TimeUTC7)

OptionTimeUTC+7 is a function type used for applying options to TimeUTC7 instances.

type TimeUTC7 added in v0.0.3

type TimeUTC7 struct {
	// contains filtered or unexported fields
}

TimeUTC7 represents a time with its location set to UTC+7, specifically for Western Indonesia Time.

func NewTimeUTC7 added in v0.0.3

func NewTimeUTC7(options ...OptionTimeUTC7) *TimeUTC7

NewTimeUTC7 creates and returns a new TimeUTC7 instance. It initializes the location to Jakarta (UTC+7) by default. Additional options can be passed to customize the TimeUTC7 instance.

Returns: - A pointer to the newly created TimeUTC7 instance.

func (*TimeUTC7) EndDate added in v0.0.3

func (t *TimeUTC7) EndDate(input time.Time) time.Time

EndDate computes the end of the day (23:59:59) for a given time in UTC+7.

Parameters: - input: The time for which to find the end of the day.

Returns: - A time.Time value representing the end of the day in UTC+7.

func (*TimeUTC7) EndDateInString added in v0.0.3

func (t *TimeUTC7) EndDateInString(inputDate string) time.Time

EndDateInString parses a given date string to find the end of the day (23:59:59) in UTC+7.

Parameters: - inputDate: The date string to parse.

Returns: - A time.Time value representing the end of the day for the parsed date in UTC+7.

func (*TimeUTC7) Now added in v0.0.3

func (t *TimeUTC7) Now() time.Time

Now returns the current time adjusted to the TimeUTC7's location (UTC+7).

Returns: - A time.Time value representing the current time in UTC+7.

func (*TimeUTC7) ParseUTC7 added in v0.0.3

func (t *TimeUTC7) ParseUTC7(timeFormat string, value string) (time.Time, error)

ParseUTC7 attempts to parse a given string into a time.Time value based on the specified format. The parsing is done considering the UTC+7 timezone. If parsing fails, the current time in UTC+7 and an error are returned.

Parameters: - timeFormat: The format for parsing the input string. - value: The string value to parse into a time.Time.

Returns: - A time.Time value representing the parsed time in UTC+7. - An error if the parsing fails.

func (*TimeUTC7) StartDate added in v0.0.3

func (t *TimeUTC7) StartDate(input time.Time) time.Time

StartDate computes the start of the day (00:00:00) for a given time in UTC+7.

Parameters: - input: The time for which to find the start of the day.

Returns: - A time.Time value representing the start of the day in UTC+7.

func (*TimeUTC7) StartDateInString added in v0.0.3

func (t *TimeUTC7) StartDateInString(inputDate string) time.Time

StartDateInString parses a given date string to find the start of the day (00:00:00) in UTC+7.

Parameters: - inputDate: The date string to parse.

Returns: - A time.Time value representing the start of the day for the parsed date in UTC+7.

Directories

Path Synopsis
examples
net
response-mapper
v1

Jump to

Keyboard shortcuts

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