README
ΒΆ
Mithril Utils Example
This example demonstrates Phase 14: Utilities & Helpers, showcasing all the utility functions available in the Mithril framework.
Features Demonstrated
π Hashing & Encryption
- Bcrypt: Password hashing with configurable cost
- Argon2: Modern password hashing with memory, time, and thread parameters
- SHA-256/SHA-512: Cryptographic hashing
- HMAC: Message authentication codes
- AES-256-GCM: Symmetric encryption with authentication
- Base64: Encoding/decoding utilities
π Pagination
- PaginationRequest: Parse pagination parameters from query strings
- PaginationResponse: Standardized paginated response format
- PaginationMeta: Complete pagination metadata
- Navigation Links: HATEOAS-style pagination links
π Sorting
- Multi-field Sorting: Sort by multiple fields with different directions
- Field Validation: Ensure only allowed fields can be sorted
- Reflection-based: Works with any struct type
- Query String Parsing: Parse sort parameters from URLs
π οΈ Helper Utilities
- String Utilities: Truncation, validation, formatting
- Number Utilities: Parsing, clamping, rounding
- Time Utilities: Human-readable durations and time ago
- Validation: Email, URL, UUID, phone, password strength
- Slice Utilities: Filter, map, reduce, chunk operations
API Endpoints
Hashing
GET /hash/bcrypt/:password- Hash password with bcryptGET /hash/argon2/:password- Hash password with argon2POST /hash/verify- Verify password against hash
Encryption
POST /encrypt- Encrypt data with AES-256-GCMPOST /decrypt- Decrypt data with verification
Pagination
GET /users?page=1&page_size=10&sort_by=name&sort_dir=asc- Paginated users with sorting
Sorting
GET /products?sort=name:asc,price:desc- Multi-field sorting
Utilities
GET /utils/string/:text- String manipulation examplesGET /utils/validation/:type/:value- Validation examplesGET /utils/format/:type/:value- Formatting examplesPOST /utils/base64/encode- Base64 encodingPOST /utils/base64/decode- Base64 decoding
Usage Examples
Hashing Passwords
# Hash with bcrypt
curl "http://localhost:3000/hash/bcrypt/mypassword"
# Hash with argon2
curl "http://localhost:3000/hash/argon2/mypassword"
# Verify password
curl -X POST "http://localhost:3000/hash/verify" \
-H "Content-Type: application/json" \
-d '{"password":"mypassword","hash":"$2a$12$...","algorithm":"bcrypt"}'
Encryption
# Encrypt data
curl -X POST "http://localhost:3000/encrypt" \
-H "Content-Type: application/json" \
-d '{"data":"sensitive information"}'
# Decrypt data
curl -X POST "http://localhost:3000/decrypt" \
-H "Content-Type: application/json" \
-d '{"data":"encrypted_data","signature":"hmac_signature","nonce":"nonce","key":"key","secret":"secret"}'
Pagination
# Get paginated users
curl "http://localhost:3000/users?page=1&page_size=5&sort_by=name&sort_dir=asc"
# Response includes:
# {
# "data": [...],
# "meta": {
# "page": 1,
# "page_size": 5,
# "total": 100,
# "total_pages": 20,
# "has_next": true,
# "has_prev": false,
# "next_page": 2,
# "prev_page": null
# },
# "links": {
# "self": "...",
# "first": "...",
# "last": "...",
# "next": "..."
# }
# }
Sorting
# Sort products by name ascending, then price descending
curl "http://localhost:3000/products?sort=name:asc,price:desc"
Validation
# Validate email
curl "http://localhost:3000/utils/validation/email/user@example.com"
# Validate UUID
curl "http://localhost:3000/utils/validation/uuid/550e8400-e29b-41d4-a716-446655440000"
# Validate password strength
curl "http://localhost:3000/utils/validation/password/MyStr0ng!Pass"
Formatting
# Format bytes
curl "http://localhost:3000/utils/format/bytes/1048576"
# Format duration
curl "http://localhost:3000/utils/format/duration/3661"
# Time ago
curl "http://localhost:3000/utils/format/time_ago/1640995200"
Code Examples
Using Hashing in Your Code
import "github.com/mithril-framework/mithril/pkg/utils"
// Hash a password
config := &utils.HashConfig{
Algorithm: utils.Bcrypt,
Cost: 12,
}
result, err := utils.Hash("mypassword", config)
// Verify a password
valid, err := utils.Verify("mypassword", result.Hash, config)
Using Encryption in Your Code
// Create encryption config
config, err := utils.NewEncryptionConfig()
// Encrypt data
encrypted, err := utils.Encrypt("sensitive data", config)
// Decrypt data
decrypted, err := utils.Decrypt(encrypted.Data, encrypted.Signature, encrypted.Nonce, config)
Using Pagination in Your Code
// Parse pagination from request
pagination := utils.ParsePaginationRequest(
c.Query("page", "1"),
c.Query("page_size", "10"),
c.Query("sort_by", "id"),
c.Query("sort_dir", "asc"),
config,
)
// Calculate offset for database query
offset := utils.CalculateOffset(pagination.Page, pagination.PageSize)
// Create paginated response
response := utils.CreatePaginationResponseWithLinks(
data,
pagination.Page,
pagination.PageSize,
total,
baseURL,
)
Using Sorting in Your Code
// Parse sort fields from query
sortFields, err := utils.ParseSortRequest("name:asc,price:desc", config)
// Sort a slice
err = utils.SortSlice(&products, sortFields)
Using Helper Utilities
// String utilities
truncated := utils.Truncate("Long text here", 10)
isEmpty := utils.IsEmpty("")
// Validation
isEmail := utils.IsValidEmail("user@example.com")
isStrong := utils.IsStrongPassword("MyStr0ng!Pass")
// Time utilities
timeAgo := utils.TimeAgo(time.Now().Add(-2 * time.Hour))
formatted := utils.FormatDuration(2 * time.Hour)
// Number utilities
min := utils.Min(5, 10)
clamped := utils.Clamp(15, 0, 10)
rounded := utils.Round(3.14159, 2)
Integration with Generated Projects
When you create a new Mithril project with mithril new project-name, all utilities are automatically available:
- Import the package:
import "github.com/mithril-framework/mithril/pkg/utils" - Use in controllers: All utilities are ready to use
- Configuration: Utilities respect your app configuration
- Validation: Integrates with the validation system
Security Considerations
- Password Hashing: Use bcrypt or argon2 for passwords, never plain SHA
- Encryption: Always use authenticated encryption (AES-GCM)
- HMAC: Use for data integrity verification
- Random Keys: Generate cryptographically secure random keys
- Validation: Always validate input data before processing
Performance Considerations
- Hashing: Bcrypt cost should be balanced between security and performance
- Argon2: Adjust memory and time parameters based on your needs
- Pagination: Use database-level pagination for large datasets
- Sorting: Consider database indexes for frequently sorted fields
This utilities package provides a solid foundation for common operations in web applications, with security and performance in mind.
Documentation
ΒΆ
There is no documentation for this package.
Click to show internal directories.
Click to hide internal directories.