helpers

package
v1.0.1-rc Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2025 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FileUploadConfig

type FileUploadConfig struct {
	MaxSize          int64
	AllowedMimeTypes []string
	TempDir          string
	Destination      string
}

UploadConfig holds upload configuration

type FileUploadResult

type FileUploadResult struct {
	OriginalName string
	SavedName    string
	MimeType     string
	Size         int64
	Path         string
}

UploadResult contains information about uploaded file

type Helpers

type Helpers struct {
	Redner           *render.Render
	FileUploadConfig FileUploadConfig
}

func (*Helpers) CreateDirIfNotExist

func (h *Helpers) CreateDirIfNotExist(path string) error

Ensure that a specific directory exists at the given path. If the directory is absent, it proceeds to create it with predefined permissions. This function is useful in scenarios where you need to guarantee that a directory is present before performing operations that require its existence. A directory that is created will have octal value allows the owner to read, write, and execute files within the directory, while the group and others can only read and execute, not alter the content. Example:

Helpers.CreateDirIfNotExist(path)

func (*Helpers) CreateFileIfNotExist

func (h *Helpers) CreateFileIfNotExist(path string) error

Ensure that a file at the given path exists. If it doesn't, it attempts to create the file. Example:

Helpers.CreateFileIfNotExist(path)

func (*Helpers) Getenv

func (h *Helpers) Getenv(key string, defaultValue ...string) string

Get environment variable or return default if the value is an empty string. Example:

Helpers.Getenv("ADELE_API_ADDR", "localhost")

func (*Helpers) NewValidator

func (h *Helpers) NewValidator(data url.Values) *Validation

Create new validator for use with a form.

Example: validator := helpers.NewValidator(r.Form)

func (*Helpers) RandomString

func (h *Helpers) RandomString(n int) string

RandomString generates a cryptographically secure random string of specified length using crypto/rand for entropy. The generated string contains alphanumeric characters (a-z, A-Z, 0-9) suitable for tokens, IDs, passwords, and other security-sensitive applications.

Example:

sessionID := helpers.RandomString(32)
// Returns: "K7mX9pQr2NvB8zYtF3wL5cR1jP6sM4xH"

apiKey := helpers.RandomString(16)
// Returns: "aB9Xm2Qr7Kp3Nv8Z"

tempPassword := helpers.RandomString(12)
// Returns: "M9sK2pR7bN4X"

func (*Helpers) Render

func (h *Helpers) Render(w http.ResponseWriter, r *http.Request, template string, variables, data interface{}) error

func (*Helpers) UploadFile

func (h *Helpers) UploadFile(r *http.Request, field string, config FileUploadConfig, fs filesystem.FS) (*FileUploadResult, error)

UploadFile safely handles multipart file uploads with validation, secure filename generation, and automatic cleanup. Validates MIME type and size, prevents path traversal attacks, and supports both local filesystem and custom storage backends. Example:

config := UploadConfig{
    MaxSize:          10 << 20, // 10MB
    AllowedMimeTypes: []string{"image/jpeg", "image/png"},
    TempDir:          "storage/tmp",
    Destination:      "storage/uploads",
}
result, err := app.UploadFile(r, "avatar", config, nil)
if err != nil {
    return fmt.Errorf("upload failed: %w", err)
}
log.Printf("Uploaded %s as %s", result.OriginalName, result.SavedName)

type Validation

type Validation struct {
	Data   url.Values
	Errors map[string]string
}

func (*Validation) AddError

func (v *Validation) AddError(key, message string)

AddError adds an error message to the validation errors map if the key doesn't already exist. The message supports :attribute placeholder which gets replaced with a formatted field name.

Example:

validator.AddError("email", "The :attribute field must be valid")
// Results in: "The email field must be valid"

func (*Validation) Check

func (v *Validation) Check(ok bool, key, message string)

Check adds an error message if the given condition is false. Useful for custom validation logic with conditional error reporting.

Example:

age, _ := strconv.Atoi(r.Form.Get("age"))
validator.Check(age >= 18, "age", "Must be 18 or older")

func (*Validation) Has

func (v *Validation) Has(field string, r *http.Request) bool

Has checks if a field exists in the HTTP request form data and has a non-empty value. Returns true if the field exists and has content, false otherwise.

Example:

if validator.Has("username", r) {
    // Field exists and has a value
}

func (*Validation) HasJSON

func (v *Validation) HasJSON(json interface{}, fields ...string)

HasJSON validates that specified fields exist in a JSON struct and contain non-empty values. Uses reflection to check both field existence and value content.

Example:

type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}
user := &User{Name: "John", Email: ""}
validator.HasJSON(user, "Name", "Email")
// Name passes, Email fails validation

func (*Validation) IsDateISO

func (v *Validation) IsDateISO(field, value string)

IsDateISO validates that a field contains a valid date in ISO format (YYYY-MM-DD). Uses Go's time.Parse with the standard date layout for validation.

Example:

birthDate := r.Form.Get("birth_date")
validator.IsDateISO("birth_date", birthDate)
// Accepts "2023-12-25", "1990-01-01", but rejects "12/25/2023", "invalid"

func (*Validation) IsEmail

func (v *Validation) IsEmail(field, value string)

IsEmail validates that a field contains a properly formatted email address. Uses the govalidator library for RFC-compliant email validation.

Example:

email := r.Form.Get("email")
validator.IsEmail("email", email)
// Validates format like "user@example.com"

func (*Validation) IsEmailInPublicDomain

func (v *Validation) IsEmailInPublicDomain(field, value string)

IsEmailInPublicDomain validates that an email address exists and is in a public domain. Uses govalidator's existence check which may perform DNS lookups.

Example:

email := r.Form.Get("email")
validator.IsEmailInPublicDomain("email", email)
// Checks if email domain is reachable and public

func (*Validation) IsFloat

func (v *Validation) IsFloat(field, value string)

IsFloat validates that a field contains a valid floating-point number. Uses strconv.ParseFloat with 64-bit precision for validation.

Example:

price := r.Form.Get("price")
validator.IsFloat("price", price)
// Accepts "12.99", "0.5", "123", but rejects "abc", "12.34.56"

func (*Validation) IsInt

func (v *Validation) IsInt(field, value string)

IsInt validates that a field contains a valid integer value. Uses strconv.Atoi for parsing validation.

Example:

quantity := r.Form.Get("quantity")
validator.IsInt("quantity", quantity)
// Accepts "123", "-45", but rejects "12.5", "abc"

func (*Validation) NoSpaces

func (v *Validation) NoSpaces(field, value string)

NoSpaces validates that a field contains no whitespace characters. Useful for usernames, slugs, or other fields that shouldn't contain spaces.

Example:

username := r.Form.Get("username")
validator.NoSpaces("username", username)
// Accepts "john_doe", "user123", but rejects "john doe", "user name"

func (*Validation) NotEmpty

func (v *Validation) NotEmpty(field, value string, message ...string)

NotEmpty validates that a field is not empty after trimming whitespace. Accepts optional custom error message, otherwise uses default message.

Example:

name := r.Form.Get("name")
validator.NotEmpty("name", name)
// Or with custom message:
validator.NotEmpty("name", name, "Name cannot be blank")

func (*Validation) Password

func (v *Validation) Password(field string, value string, length ...int)

Password validates that a password meets security requirements including minimum length, mixed case letters. Default minimum length is 12 characters.

Example:

password := r.Form.Get("password")
validator.Password("password", password)        // Uses default 12 char minimum
validator.Password("password", password, 8)     // Uses custom 8 char minimum
// Requires uppercase, lowercase, and minimum length

func (*Validation) PasswordUncompromised

func (v *Validation) PasswordUncompromised(field string, value string, threshold ...int)

PasswordUncompromised checks if a password appears in known data breaches using the HaveIBeenPwned API with k-anonymity (only sends first 5 chars of SHA1 hash). Optional threshold parameter sets minimum breach count to trigger error (default: 1).

Example:

password := r.Form.Get("password")
validator.PasswordUncompromised("password", password)     // Any breach count fails
validator.PasswordUncompromised("password", password, 5)  // Only fails if seen 5+ times
// Checks against HaveIBeenPwned database securely

func (*Validation) Required

func (v *Validation) Required(r *http.Request, fields ...string)

Required validates that specified fields exist and are not empty in the HTTP request form. Adds error messages for any missing or empty required fields.

Example:

validator.Required(r, "name", "email", "password")
// Checks that all three fields have values

func (*Validation) RequiredJSON

func (v *Validation) RequiredJSON(json interface{}, fields ...string)

RequiredJSON validates that specified fields exist in a JSON struct using reflection. Checks if the provided interface contains the required fields as struct properties.

Example:

type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}
user := &User{}
validator.RequiredJSON(user, "Name", "Email")

func (*Validation) ToString

func (v *Validation) ToString() string

ToString converts the Validation.Errors map to a human-readable string format. Useful for displaying all validation errors as a single message.

Example:

validator.Required(r, "name", "email")
if !validator.Valid() {
    errorString := validator.ToString()
    // Returns: " Name is required Email is required"
}

func (*Validation) Valid

func (v *Validation) Valid() bool

Test if any errors exist.

Example:

if !validator.Valid() {
	... Handle validation fail
}

Jump to

Keyboard shortcuts

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