Documentation
¶
Index ¶
- func BindJSON(r *http.Request, dst interface{}) error
- func Capitalize(s string) string
- func CheckPassword(hash, password string) bool
- func ContainsAny(s string, substrs ...string) bool
- func FromBase64(encoded string) (string, error)
- func GenerateOTP(length int, charset string) (string, error)
- func GetBearerToken(r *http.Request) string
- func GetHeader(r *http.Request, key string) string
- func GetIP(r *http.Request) string
- func HMACSHA256(secret, data string) string
- func HashPassword(password string) (string, error)
- func IsAlphaNumeric(s string) bool
- func IsEmailValid(email string) bool
- func IsEmpty(s string) bool
- func IsJSONRequest(r *http.Request) bool
- func IsNumeric(s string) bool
- func IsSlug(s string) bool
- func IsStrongPassword(p string) bool
- func MaskEmail(email string) string
- func NoContent(w http.ResponseWriter)
- func NormalizeEmail(email string) string
- func RandomString(n int) (string, error)
- func RemoveWhitespace(s string) string
- func RespondWithError(w http.ResponseWriter, status int, message string) error
- func RespondWithJSON(w http.ResponseWriter, status int, payload interface{}) error
- func RouteContext(r *http.Request) *chi.Context
- func Slugify(s string) string
- func ToBase64(data string) string
- func ToHex(data string) string
- func Truncate(s string, max int, withEllipsis bool) string
- func URLParam(r *http.Request, key string) string
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BindJSON ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
IsEmpty returns true if the input string is empty or contains only whitespace.
Example:
IsEmpty(" ") // Output: true
IsEmpty("text") // Output: false
func IsJSONRequest ¶
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 ¶
IsNumeric returns true if the string contains only numeric digits (0-9).
Example:
IsNumeric("12345") // Output: true
IsNumeric("123a5") // Output: false
func IsSlug ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ToBase64 encodes the input string into a base64-encoded string.
Example:
encoded := ToBase64("hello world")
fmt.Println(encoded) // Output: "aGVsbG8gd29ybGQ="
func ToHex ¶
ToHex encodes the input string into its hexadecimal representation.
Example:
hexStr := ToHex("hello")
fmt.Println(hexStr) // Output: "68656c6c6f"
func Truncate ¶
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"
Types ¶
This section is empty.