helpers

package
v2.0.5 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BindJSON

func BindJSON(r *http.Request, dst interface{}) error

BindJSON decodes the JSON payload from the request body into the destination struct.

It closes the request body after reading and disallows unknown JSON fields.

Example:

var payload MyStruct
err := BindJSON(r, &payload)
if err != nil {
    // handle JSON decoding error
}

func Capitalize

func Capitalize(s string) string

Capitalize converts the first character of the string to uppercase, leaving the rest of the string unchanged.

Example:

Capitalize("hello") // Output: "Hello"
Capitalize("")      // Output: ""

func CheckPassword

func CheckPassword(hash, password string) bool

CheckPassword compares a bcrypt hashed password with its possible plaintext equivalent.

Returns true if the password matches the hash, false otherwise.

Example:

valid := CheckPassword("$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36G1e15Ny5rQmj.LrZIvVbG", "mysecretpassword")
fmt.Println(valid) // Output: true

func ContainsAny

func ContainsAny(s string, substrs ...string) bool

ContainsAny returns true if the string s contains any of the provided substrings.

Example:

ContainsAny("hello world", "test", "world")  // Output: true
ContainsAny("hello world", "test", "abc")    // Output: false

func FromBase64

func FromBase64(encoded string) (string, error)

FromBase64 decodes a base64-encoded string back to its original string form.

It returns the decoded string and any error encountered during decoding.

Example:

decoded, err := FromBase64("aGVsbG8gd29ybGQ=")
if err != nil {
    // handle error
}
fmt.Println(decoded) // Output: "hello world"

func GenerateOTP

func GenerateOTP(length int, charset string) (string, error)

GenerateOTP generates a random OTP (One-Time Password) string of the specified length, using characters from the provided charset.

If charset is empty, it defaults to "23456789ABCDEFGHJKLMNPQRSTUVWXYZ".

Returns an error if length is zero or negative, or if random generation fails.

Example:

otp, err := GenerateOTP(6, "")
if err != nil {
    // handle error
}
fmt.Println(otp) // Output: "7G4K2H"

func GetBearerToken

func GetBearerToken(r *http.Request) string

GetBearerToken extracts the Bearer token from the Authorization header of the request.

If the Authorization header does not start with "Bearer ", an empty string is returned.

Example:

token := GetBearerToken(r)
fmt.Println(token) // Output: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

func GetHeader

func GetHeader(r *http.Request, key string) string

GetHeader safely retrieves the value of the specified HTTP header key from the request, trimming any leading or trailing whitespace.

Example:

val := GetHeader(r, "X-Custom-Header")
fmt.Println(val) // Output: "header-value"

func GetIP

func GetIP(r *http.Request) string

GetIP attempts to retrieve the real client IP address from the HTTP request, accounting for common proxy headers such as "X-Forwarded-For" and "X-Real-IP".

If those headers are not set, it falls back to parsing the remote address.

Example:

ip := GetIP(r)
fmt.Println(ip) // Output: "203.0.113.195"

func HMACSHA256

func HMACSHA256(secret, data string) string

HMACSHA256 generates a base64-encoded HMAC using SHA-256 for the given data and secret key.

It returns the resulting HMAC string.

Example:

hmac := HMACSHA256("mysecretkey", "data to protect")
fmt.Println(hmac) // Output: "XUFAKrxLKna5cZ2REBfFkg=="

func HashPassword

func HashPassword(password string) (string, error)

HashPassword hashes the provided plaintext password using bcrypt algorithm.

It returns the hashed password string and any error encountered during hashing.

Example:

hash, err := HashPassword("mysecretpassword")
if err != nil {
    // handle error
}
fmt.Println(hash) // Output: $2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36G1e15Ny5rQmj.LrZIvVbG

func IsAlphaNumeric

func IsAlphaNumeric(s string) bool

IsAlphaNumeric returns true if the string contains only letters (a-z, A-Z) and digits (0-9).

Example:

IsAlphaNumeric("abc123")  // Output: true
IsAlphaNumeric("abc_123") // Output: false

func IsEmailValid

func IsEmailValid(email string) bool

IsEmailValid performs basic validation to check if the provided email string matches a simple email format pattern.

This validation is not fully RFC compliant but is sufficient for common cases.

It returns true if the email is valid, false otherwise.

Example:

valid := IsEmailValid("example.user+test@gmail.com")
fmt.Println(valid) // Output: true

valid = IsEmailValid("invalid-email@@domain.com")
fmt.Println(valid) // Output: false

func IsEmpty

func IsEmpty(s string) bool

IsEmpty returns true if the input string is empty or contains only whitespace.

Example:

IsEmpty("   ")  // Output: true
IsEmpty("text") // Output: false

func IsJSONRequest

func IsJSONRequest(r *http.Request) bool

IsJSONRequest checks if the Content-Type header of the request indicates JSON content.

Returns true if Content-Type starts with "application/json".

Example:

if IsJSONRequest(r) {
    // handle JSON request
}

func IsNumeric

func IsNumeric(s string) bool

IsNumeric returns true if the string contains only numeric digits (0-9).

Example:

IsNumeric("12345")  // Output: true
IsNumeric("123a5")  // Output: false

func IsSlug

func IsSlug(s string) bool

IsSlug returns true if the string is a valid URL slug containing only lowercase letters, digits, and hyphens.

Example:

IsSlug("my-slug-123")  // Output: true
IsSlug("My_Slug")      // Output: false

func IsStrongPassword

func IsStrongPassword(p string) bool

IsStrongPassword performs a basic password strength check.

The password must be at least 8 characters and contain at least one uppercase letter, one number, and one symbol from !@#~$%^&*()+|_

Example:

IsStrongPassword("Passw0rd!") // Output: true
IsStrongPassword("password")  // Output: false

func MaskEmail

func MaskEmail(email string) string

If the local part is 1 character or less, the email is returned unchanged.

Example:

masked := MaskEmail("example@gmail.com")
fmt.Println(masked) // Output: "e******@gmail.com"

masked = MaskEmail("a@domain.com")
fmt.Println(masked) // Output: "a@domain.com"

func NoContent

func NoContent(w http.ResponseWriter)

NoContent sends an HTTP 204 No Content response without a body.

Example:

NoContent(w)  // Sends HTTP status 204 with empty body

func NormalizeEmail

func NormalizeEmail(email string) string

NormalizeEmail trims leading and trailing spaces from the email string and converts it to lowercase.

Example:

normalized := NormalizeEmail("  ExAmple@Domain.Com  ")
fmt.Println(normalized) // Output: "example@domain.com"

func RandomString

func RandomString(n int) (string, error)

RandomString generates a random alphanumeric string of length n.

Returns an error if the random byte generation fails.

Example:

str, err := RandomString(10)
if err == nil {
    fmt.Println(str) // Output: e.g. "4f2a1c9b8e"
}

func RemoveWhitespace

func RemoveWhitespace(s string) string

RemoveWhitespace removes all whitespace characters (spaces, tabs, newlines) from the string.

Example:

RemoveWhitespace("a b \n c\t")  // Output: "abc"

func RespondWithError

func RespondWithError(w http.ResponseWriter, status int, message string) error

RespondWithError writes a JSON response containing an error message with the specified HTTP status code.

It uses RespondWithJSON internally to send a standardized error response of the form: {"error": "message"}

Returns any error encountered during JSON encoding.

Example:

err := RespondWithError(w, http.StatusBadRequest, "invalid request payload")
if err != nil {
    // handle error
}

func RespondWithJSON

func RespondWithJSON(w http.ResponseWriter, status int, payload interface{}) error

RespondWithJSON writes the given payload as a JSON response with the specified HTTP status code.

It sets the "Content-Type" header to "application/json" and writes the status code before encoding.

Returns any error encountered during JSON encoding.

Example:

err := RespondWithJSON(w, http.StatusOK, map[string]string{"message": "success"})
if err != nil {
    // handle error
}

func RouteContext

func RouteContext(r *http.Request) *chi.Context

RouteContext retrieves the *chi.Context from the request's context, allowing access to route parameters and routing information.

Example:

ctx := RouteContext(r)
fmt.Println(ctx.RoutePattern())

func Slugify

func Slugify(s string) string

Slugify converts a string to a URL-friendly slug: lowercase, alphanumeric with words separated by hyphens.

Example:

Slugify("Hello, World!")  // Output: "hello-world"

func ToBase64

func ToBase64(data string) string

ToBase64 encodes the input string into a base64-encoded string.

Example:

encoded := ToBase64("hello world")
fmt.Println(encoded) // Output: "aGVsbG8gd29ybGQ="

func ToHex

func ToHex(data string) string

ToHex encodes the input string into its hexadecimal representation.

Example:

hexStr := ToHex("hello")
fmt.Println(hexStr) // Output: "68656c6c6f"

func Truncate

func Truncate(s string, max int, withEllipsis bool) string

Truncate shortens the string to a maximum length `max`. If the string exceeds `max` and `withEllipsis` is true, it appends "..." at the end.

If max is less than or equal to 3, ellipsis is ignored and string is truncated strictly.

Examples:

Truncate("Hello, World", 8, true)  // Output: "Hello..."
Truncate("Hello", 10, true)        // Output: "Hello"

func URLParam

func URLParam(r *http.Request, key string) string

URLParam extracts a URL parameter value from the request using the chi router.

Example:

userID := URLParam(r, "userID")
fmt.Println(userID) // Output: "12345"

Types

This section is empty.

Jump to

Keyboard shortcuts

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