helpers

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2024 License: MIT Imports: 22 Imported by: 5

Documentation

Index

Constants

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`
	DateMonthFormat            = `02 January 2006`
	DateMonthFormatWithoutYear = `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 to Bulan
	MappingMonthToBulan = 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 CheckArrayIntNil

func CheckArrayIntNil(data []int) []int

handle not return nil

func CheckIntValue

func CheckIntValue(data *int) int

Return 0 if data is nil, otherwise return the value of data

func CheckStringValue

func CheckStringValue(data *string) string

Return empty string if data is nil, otherwise return the value of data

func CheckStringValueToPointer

func CheckStringValueToPointer(data string) *string

Return a pointer to a string or nil if the input string is empty or only contains whitespace

func CheckTimeIsZeroToPointer

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

func CheckTimeIsZeroToString

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

func CheckTimePointerToString

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

func CheckTimePointerValue

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

func EndDate

func EndDate(t time.Time) time.Time

it will return ex 2009-11-10 23:59:59

func EndDateString

func EndDateString(t string) time.Time

it will return ex 2009-11-10 23:59:59

func ErrHashPasswordFailed

func ErrHashPasswordFailed() error

func ErrNewPasswordNotMatchWithConfirmPassword

func ErrNewPasswordNotMatchWithConfirmPassword() error

func ErrPasswordNotMatch

func ErrPasswordNotMatch() error

func FormatValidationError

func FormatValidationError(err error) error

FormatValidationError function is used to format validation errors that occur during user input validation. It changes the default format of errors from github.com/go-playground/validator/v10.

This function iterates over the validation errors and constructs a formatted error message. The error message is then translated into the Indonesian language using the Translate function. The resulting error message is then returned as a ResponseError struct.

Parameters: - err: The validation errors that occurred.

Returns: - error: The formatted validation error.

func GenerateRandomNumber

func GenerateRandomNumber(length int) string

GenerateRandomNumber generates a random number of the specified length (length int) and returns it as a string (string).

func GetHTTPRequestJSON

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

GetHTTPRequestJSON ...

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 ...

func HashPassword

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

func IsValidEmail

func IsValidEmail(email string) bool

validation email format example here: https://go.dev/play/p/j4B4v01Qolw

func IsValidUUID

func IsValidUUID(input string) bool

func PanicRecover

func PanicRecover(opName string)

func ParseUTC7

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

ParseUTC7 ...

func PasswordValid

func PasswordValid(h, p string) bool

func PrettyStruct

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

func QueryEscape

func QueryEscape(s string) string

encode value param url

func RenderJSON

func RenderJSON(w http.ResponseWriter, statusCode int, v interface{})

func RoundFloat

func RoundFloat(val float64, precision uint) float64

Round float generator example here: https://go.dev/play/p/VmTGHhV2_WI

func SafeJsonMarshal

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

SafeJsonMarshal safely marshals an interface{} to a []byte using json.Marshal. If there is an error during the marshal, it will re-marshal the original data and return it. It returns a []byte and an error. If there is an error during the marshal, the error will be returned. Otherwise, nil will be returned.

func StartDate

func StartDate(t time.Time) time.Time

it will return 2009-11-10 00:00:00

func StartDateString

func StartDateString(t string) time.Time

it will return 2009-11-10 00:00:00

func StatusCodeMapping

func StatusCodeMapping(statusCode int, v interface{}) int

func StatusErrorMapping

func StatusErrorMapping(code int) int

func StatusMapping

func StatusMapping(statusCode int) string

StatusMapping maps HTTP status code to a descriptive string. It returns the descriptive string that can be used as the 'status' field in ResponseDefault.

func StreamToByte

func StreamToByte(stream io.Reader) []byte

StreamToByte ...

func StreamToString

func StreamToString(stream io.Reader) string

StreamToString func

func TimeZoneJakarta

func TimeZoneJakarta() *time.Location

func ToLower

func ToLower(input string) string

Lower case a string, ex; HELLO WORLD => hello world

func ToSentenceCase

func ToSentenceCase(input string) string

Sentence case in a string, ex; hello world => Hello world

func ToTitle

func ToTitle(input string) string

Capitalize each word in a string, ex; hello world => Hello World

func ToUpper

func ToUpper(input string) string

Upper case a string, ex; hello world => HELLO WORLD

func Translate

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

func WriteJSON

func WriteJSON(w http.ResponseWriter, statusCode int, v interface{}) error

WriteJSON writes the JSON representation of v to the response writer w, and sets the status code of the response to statusCode. It returns an error if there was an error during the operation.

Types

type CustomConfigClientRequest

type CustomConfigClientRequest struct {
	Timeout int
}

func (*CustomConfigClientRequest) SetTimeout

func (c *CustomConfigClientRequest) SetTimeout(defaultTimeout int) int

type Meta

type Meta struct {
	Page         int `json:"page,omitempty"`
	Limit        int `json:"limit,omitempty"`
	TotalRecords int `json:"total_records,omitempty"`
	TotalPages   int `json:"total_pages,omitempty"`
}

Meta struct

type MultiLanguages

type MultiLanguages struct {
	ID string `json:"id"`
	EN string `json:"en"`
}

func NewResponseMultiLang

func NewResponseMultiLang(languages MultiLanguages) *MultiLanguages

func (*MultiLanguages) Error

func (e *MultiLanguages) Error() string

type Pagination

type Pagination struct {
	Meta Meta
	Data interface{}
}

type ResponseDefault

type ResponseDefault struct {
	Status  string      `json:"status"`
	Message string      `json:"message,omitempty"`
	Meta    interface{} `json:"meta,omitempty"`
	Data    interface{} `json:"data,omitempty"`
}

type ResponseError

type ResponseError struct {
	Status  string         `json:"status"`
	Code    int            `json:"code"`
	Err     error          `json:"-"`
	Message MultiLanguages `json:"message"`
}

func ErrCannotBeMoreThan

func ErrCannotBeMoreThan(id, en, max string) *ResponseError

func ErrCannotHaveAccessResources

func ErrCannotHaveAccessResources() *ResponseError

func ErrCannotHaveAccessUpdateData

func ErrCannotHaveAccessUpdateData() *ResponseError

func ErrCannotUpdateData

func ErrCannotUpdateData() *ResponseError

func ErrCreatedDB

func ErrCreatedDB() *ResponseError

func ErrDB

func ErrDB() *ResponseError

func ErrDataNotFound

func ErrDataNotFound(id, en string) *ResponseError

func ErrEmailIsVerified

func ErrEmailIsVerified() *ResponseError

func ErrEmailNotVerified

func ErrEmailNotVerified() *ResponseError

func ErrFailedSendEmail

func ErrFailedSendEmail() *ResponseError

func ErrFailedTranslateText

func ErrFailedTranslateText() *ResponseError

func ErrGenerateOtp

func ErrGenerateOtp() *ResponseError

func ErrGetRequest

func ErrGetRequest() *ResponseError

func ErrInvalid

func ErrInvalid(id, en string) *ResponseError

func ErrInvalidFormat

func ErrInvalidFormat(id, en string) *ResponseError

func ErrIsDuplicate

func ErrIsDuplicate(id, en string) *ResponseError

func ErrIsEmpty

func ErrIsEmpty(id, en string) *ResponseError

func ErrIsRequired

func ErrIsRequired(id, en string) *ResponseError

func ErrMaxCharacters

func ErrMaxCharacters(id, en, max string) *ResponseError

func ErrMinCharacters

func ErrMinCharacters(id, en, min string) *ResponseError

func ErrMustBeMoreThanZero

func ErrMustBeMoreThanZero(id, en string) *ResponseError

func ErrNotAccess

func ErrNotAccess() *ResponseError

func ErrNotFound

func ErrNotFound() *ResponseError

func ErrOtpExpired

func ErrOtpExpired() *ResponseError

func ErrOtpInvalid

func ErrOtpInvalid() *ResponseError

func ErrReadContext

func ErrReadContext() *ResponseError

func ErrRouteNotFound

func ErrRouteNotFound() *ResponseError

func ErrTooLong

func ErrTooLong(id, en string) *ResponseError

func ErrTooMany

func ErrTooMany(id, en string) *ResponseError

func ErrTooShort

func ErrTooShort(id, en string) *ResponseError

func ErrUnmarshalJSON

func ErrUnmarshalJSON() *ResponseError

func ErrUpdatedDB

func ErrUpdatedDB() *ResponseError

func NewError

func NewError(code TypeError, err error) *ResponseError

func (*ResponseError) Error

func (e *ResponseError) Error() string

type ResponseErrorHttp

type ResponseErrorHttp struct {
	Status  string         `json:"status"`
	Code    int            `json:"code"`
	Desc    MultiLanguages `json:"desc"`
	Message MultiLanguages `json:"message"`
}

unmarshal from response http

func (*ResponseErrorHttp) GetMessageEN

func (m *ResponseErrorHttp) GetMessageEN() string

func (*ResponseErrorHttp) GetMessageID

func (m *ResponseErrorHttp) GetMessageID() string

type TypeError

type TypeError uint16
const (
	ErrForbidden    TypeError = iota + 10 // 10
	ErrUnauthorized                       // 11
	ErrDatabase                           // 12
	ErrConflict                           // 13
	ErrFromUseCase                        // 14
	ErrValidation                         // 15
	ErrNoFound                            // 16
	ErrUnknown                            // 17
)

Jump to

Keyboard shortcuts

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