Documentation
¶
Index ¶
- Variables
- func BadRequest(c *gin.Context, message string)
- func BindForm(c *gin.Context, obj interface{}) bool
- func BindHeader(c *gin.Context, obj interface{}) bool
- func BindJSON(c *gin.Context, obj interface{}) bool
- func BindQuery(c *gin.Context, obj interface{}) bool
- func BindURI(c *gin.Context, obj interface{}) bool
- func BuildFilterArgs(filterMap map[string]string) filters.Args
- func CORSMiddleware(allowOrigins []string, allowMethods []string, allowHeaders []string, ...) gin.HandlerFunc
- func CSVResponse(c *gin.Context, data []byte, filename string)
- func Conflict(c *gin.Context, message string)
- func ContainsString(slice []string, str string) bool
- func ConvertJSONMapToStringMap(jsonMap models.JSONMap) map[string]string
- func CreateHTTPClient(config HTTPClientConfig) *http.Client
- func EncodeRegistryAuth(authConfig models.RegistryAuth) (string, error)
- func EnsureImage(ctx context.Context, cli DockerClient, imageName string, pull bool, ...) error
- func EnsureNetwork(ctx context.Context, cli DockerClient, networkName string, driver string, ...) (string, error)
- func EnsureVolume(ctx context.Context, cli DockerClient, volumeName string, driver string, ...) (string, error)
- func ErrorResponse(c *gin.Context, statusCode int, code, message, details string)
- func FileExists(filename string) bool
- func FileResponse(c *gin.Context, data []byte, filename, contentType string)
- func Forbidden(c *gin.Context, message string)
- func FormatContainerStatus(state string, health *types.Health) string
- func FormatImageSize(sizeBytes int64) string
- func FormatLabels(labels map[string]string) []string
- func FromJSON(data []byte, obj interface{}) error
- func GenerateRequestID() string
- func GetClientIP(c *gin.Context) string
- func GetContainerByID(ctx context.Context, cli DockerClient, id string) (*types.Container, error)
- func GetContainerByName(ctx context.Context, cli DockerClient, name string) (*types.Container, error)
- func GetContainerIP(networkSettings *types.NetworkSettings) string
- func GetContainerLogs(ctx context.Context, cli DockerClient, containerID string, ...) (io.ReadCloser, error)
- func GetExternalResourceName(external interface{}, defaultName string) string
- func GetPaginationParams(c *gin.Context) (page int, pageSize int)
- func GetRequestID(c *gin.Context) string
- func GetResourceName(projectName, prefix, name string) string
- func HashPassword(password string) (string, error)
- func InspectNetwork(ctx context.Context, cli DockerClient, networkID string) (network.Inspect, error)
- func InspectVolume(ctx context.Context, cli DockerClient, volumeID string) (volume.Volume, error)
- func InternalServerError(c *gin.Context, message string)
- func IsContainerRunning(state string) bool
- func IsExternalResource(external interface{}) bool
- func IsSensitiveField(field string) bool
- func IsValidContentType(contentType string, allowedTypes []string) bool
- func IsValidURL(str string) bool
- func JSONResponse(c *gin.Context, data []byte, filename string)
- func ListImages(ctx context.Context, cli DockerClient, options image.ListOptions) ([]image.Summary, error)
- func ListNetworks(ctx context.Context, cli DockerClient, options network.ListOptions) ([]network.Summary, error)
- func ListVolumes(ctx context.Context, cli DockerClient, filter filters.Args) (volume.ListResponse, error)
- func LoggingMiddleware(logger *logrus.Logger) gin.HandlerFunc
- func MapToStruct(m map[string]interface{}, obj interface{}) error
- func MethodNotAllowed(c *gin.Context, message string)
- func NoContentResponse(c *gin.Context)
- func NotFound(c *gin.Context, message string)
- func PaginateResults(results interface{}, page, perPage int) (interface{}, int, int, error)
- func PaginatedResponse(c *gin.Context, data interface{}, page, perPage, total int)
- func ParseContainerLabels(dockerLabels map[string]string) map[string]interface{}
- func ParseImageName(ref string) (reference.Named, error)
- func ParseRepositoryTag(refStr string) (repository string, tag string)
- func RateLimitMiddleware(limiter *RateLimiter) gin.HandlerFunc
- func RecoveryMiddleware() gin.HandlerFunc
- func RedactSensitiveData(data map[string]interface{}) map[string]interface{}
- func RemoveNetwork(ctx context.Context, cli DockerClient, networkIDOrName string, ...) error
- func RemoveVolume(ctx context.Context, cli DockerClient, volumeIDOrName string, force bool, ...) error
- func RequestIDMiddleware() gin.HandlerFunc
- func SanitizeDockerName(name string) string
- func SanitizeHTML(input string) string
- func SanitizeHeaders(headers map[string]string) map[string]string
- func SanitizeValue(field string, value interface{}) string
- func SecureHeaders(c *gin.Context)
- func ServiceUnavailable(c *gin.Context, message string)
- func SortNetworks(networks []*models.Network, sortBy string, sortOrder string) []*models.Network
- func StatusAccepted(c *gin.Context, message string)
- func StringHasPrefix(s, prefix string) bool
- func StructToMap(obj interface{}) (map[string]interface{}, error)
- func SuccessResponse(c *gin.Context, data interface{})
- func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc
- func ToJSON(obj interface{}) ([]byte, error)
- func TooManyRequests(c *gin.Context, message string)
- func Unauthorized(c *gin.Context, message string)
- func UnprocessableEntity(c *gin.Context, message string)
- func ValidateCSRFToken(c *gin.Context, token string) bool
- func ValidateContainerName(name string, options ...ValidationOptions) error
- func ValidateEmail(email string, options ...ValidationOptions) error
- func ValidateFilename(filename string, options ...ValidationOptions) error
- func ValidateIPAddress(ip string, options ...ValidationOptions) error
- func ValidateImageName(name string, options ...ValidationOptions) error
- func ValidateJSONInput(jsonStr string, maxDepth int, options ...ValidationOptions) error
- func ValidateNetworkName(name string, options ...ValidationOptions) error
- func ValidatePassword(password string, options ...ValidationOptions) error
- func ValidatePath(path string, options ...ValidationOptions) error
- func ValidatePathHTTP(path string) bool
- func ValidatePort(port int) error
- func ValidatePortString(port string) error
- func ValidateRequestHeaders(c *gin.Context, config map[string]string) bool
- func ValidateURL(rawURL string, allowedSchemes []string, options ...ValidationOptions) error
- func ValidateUsername(username string, options ...ValidationOptions) error
- func ValidateVolumeName(name string, options ...ValidationOptions) error
- func VerifyPassword(password, hash string) bool
- func XMLResponse(c *gin.Context, data []byte, filename string)
- type APIError
- type DockerClient
- type HTTPClientConfig
- type HTTPResponse
- type Meta
- type RateLimiter
- type Response
- type Throttle
- type ValidationError
- type ValidationOptions
- type ValidationResult
- func NewValidationResult() *ValidationResult
- func ValidateContainerSecurityOptions(container types.Container) *ValidationResult
- func ValidateCredentials(username, password string, options ...ValidationOptions) *ValidationResult
- func ValidateSecurityOpts(opts []string) *ValidationResult
- func ValidateStruct(s interface{}) *ValidationResult
- func (vr *ValidationResult) AddError(field, code, message string, value ...interface{})
- func (vr *ValidationResult) ErrorMessages() []string
- func (vr *ValidationResult) ErrorsByField() map[string]string
- func (vr *ValidationResult) First() *ValidationError
- func (vr *ValidationResult) GetErrors() []*ValidationError
- func (vr *ValidationResult) IsValid() bool
- func (vr *ValidationResult) MergeResults(other *ValidationResult)
- func (vr *ValidationResult) ToJSON() (string, error)
Constants ¶
This section is empty.
Variables ¶
var ( // Common errors ErrInvalidRequest = errors.New("invalid request") ErrRequestTimeout = errors.New("request timeout") ErrForbidden = errors.New("forbidden") ErrNotFound = errors.New("not found") ErrMethodNotAllowed = errors.New("method not allowed") ErrTooManyRequests = errors.New("too many requests") ErrInternalServerError = errors.New("internal server error") ErrBadGateway = errors.New("bad gateway") ErrGatewayTimeout = errors.New("gateway timeout") // Security-related errors ErrContentTypeNotAllowed = errors.New("content type not allowed") ErrInvalidContentLength = errors.New("invalid content length") ErrRequestEntityTooLarge = errors.New("request entity too large") ErrInvalidHostHeader = errors.New("invalid host header") ErrCSRFValidationFailed = errors.New("CSRF validation failed") ErrIPAddressBlocked = errors.New("IP address blocked") ErrRateLimitExceeded = errors.New("rate limit exceeded") )
var ( // ErrThrottleContextCanceled indicates the context was canceled while waiting ErrThrottleContextCanceled = errors.New("context canceled while waiting for throttle") // ErrThrottleInvalidParams indicates invalid parameters for the throttle ErrThrottleInvalidParams = errors.New("invalid throttle parameters: limit must be > 0 and interval must be > 0") )
var ( DefaultOptions = ValidationOptions{ MaxLength: 256, MinLength: 1, Required: true, StrictMode: false, } StrictOptions = ValidationOptions{ MaxLength: 256, MinLength: 1, Required: true, StrictMode: true, } SecurityOptions = ValidationOptions{ MaxLength: 64, MinLength: 8, Required: true, StrictMode: true, SanitizeOutput: true, } )
Default validation options
Functions ¶
func BadRequest ¶
BadRequest returns a 400 Bad Request response
func BindHeader ¶
BindHeader binds the header values to the given struct with error handling
func BuildFilterArgs ¶
BuildFilterArgs constructs a filters.Args object from a map of filter key-value pairs. It skips empty values to avoid sending empty filters to the Docker API.
func CORSMiddleware ¶
func CORSMiddleware(allowOrigins []string, allowMethods []string, allowHeaders []string, maxAge int) gin.HandlerFunc
CORSMiddleware creates a middleware that adds CORS headers
func CSVResponse ¶
CSVResponse sends a CSV file as response
func ContainsString ¶
ContainsString checks if a slice of strings contains a specific string. Case-insensitive comparison. NOTE: This specific implementation is not used by network_controller.go anymore, but kept here in case it's used elsewhere or intended for a different purpose.
func ConvertJSONMapToStringMap ¶
ConvertJSONMapToStringMap converts models.JSONMap to map[string]string
func CreateHTTPClient ¶
func CreateHTTPClient(config HTTPClientConfig) *http.Client
CreateHTTPClient creates an HTTP client with the given configuration
func EncodeRegistryAuth ¶
func EncodeRegistryAuth(authConfig models.RegistryAuth) (string, error)
EncodeRegistryAuth encodes registry authentication details into a base64 string suitable for the X-Registry-Auth header.
func EnsureImage ¶
func EnsureImage(ctx context.Context, cli DockerClient, imageName string, pull bool, logger *logrus.Logger) error
EnsureImage checks if an image exists locally, pulling it if necessary.
func EnsureNetwork ¶
func EnsureNetwork(ctx context.Context, cli DockerClient, networkName string, driver string, labels map[string]string, enableIPv6 bool, internal bool, attachable bool, logger *logrus.Logger) (string, error)
EnsureNetwork checks if a network exists, creating it if necessary.
func EnsureVolume ¶
func EnsureVolume(ctx context.Context, cli DockerClient, volumeName string, driver string, driverOpts map[string]string, labels map[string]string, logger *logrus.Logger) (string, error)
EnsureVolume checks if a volume exists, creating it if necessary.
func ErrorResponse ¶
ErrorResponse returns a standardized error response
func FileExists ¶
FileExists checks if a file exists and is not a directory.
func FileResponse ¶
FileResponse sends a file as response
func FormatContainerStatus ¶
FormatContainerStatus determines a user-friendly status string based on state and health. Note: This logic might need refinement based on specific desired statuses.
func FormatImageSize ¶
FormatImageSize converts bytes to a human-readable string (KB, MB, GB).
func FormatLabels ¶
FormatLabels converts a map of labels into a slice of "key=value" strings. Returns an empty slice if the input map is nil or empty.
func GenerateRequestID ¶
func GenerateRequestID() string
GenerateRequestID generates a unique request ID
func GetClientIP ¶
GetClientIP returns the client IP address
func GetContainerByID ¶
GetContainerByID finds a container by its full or partial ID.
func GetContainerByName ¶
func GetContainerByName(ctx context.Context, cli DockerClient, name string) (*types.Container, error)
GetContainerByName finds a container by its exact name.
func GetContainerIP ¶
func GetContainerIP(networkSettings *types.NetworkSettings) string
GetContainerIP extracts the primary IP address from the container's network settings. It iterates through the networks and returns the first valid IP found. Returns an empty string if no IP address is found.
func GetContainerLogs ¶
func GetContainerLogs(ctx context.Context, cli DockerClient, containerID string, options container.LogsOptions) (io.ReadCloser, error)
GetContainerLogs retrieves logs for a specific container.
func GetExternalResourceName ¶
GetExternalResourceName gets the name of an external resource from compose config.
func GetPaginationParams ¶
GetPaginationParams extracts page and page_size from query parameters with defaults and limits.
func GetRequestID ¶
GetRequestID retrieves the request ID from the context
func GetResourceName ¶
GetResourceName generates the full resource name based on project and prefix. Follows Docker Compose naming convention (project_name) if prefix is empty.
func HashPassword ¶
HashPassword hashes a password using bcrypt.
func InspectNetwork ¶
func InspectNetwork(ctx context.Context, cli DockerClient, networkID string) (network.Inspect, error)
InspectNetwork inspects a specific network.
func InspectVolume ¶
InspectVolume inspects a specific volume.
func InternalServerError ¶
InternalServerError returns a 500 Internal Server Error response
func IsContainerRunning ¶
IsContainerRunning checks if the container state indicates it's running.
func IsExternalResource ¶
func IsExternalResource(external interface{}) bool
IsExternalResource checks if a resource is marked as external in compose files.
func IsSensitiveField ¶
IsSensitiveField checks if a field is sensitive and should not be logged
func IsValidContentType ¶
IsValidContentType checks if the content type is valid
func JSONResponse ¶
JSONResponse sends a JSON file as response
func ListImages ¶
func ListImages(ctx context.Context, cli DockerClient, options image.ListOptions) ([]image.Summary, error)
ListImages lists Docker images based on filters.
func ListNetworks ¶
func ListNetworks(ctx context.Context, cli DockerClient, options network.ListOptions) ([]network.Summary, error)
ListNetworks lists Docker networks based on filters.
func ListVolumes ¶
func ListVolumes(ctx context.Context, cli DockerClient, filter filters.Args) (volume.ListResponse, error)
ListVolumes lists Docker volumes based on filters.
func LoggingMiddleware ¶
func LoggingMiddleware(logger *logrus.Logger) gin.HandlerFunc
LoggingMiddleware creates a middleware that logs requests
func MapToStruct ¶
MapToStruct converts a map to a struct using JSON tags
func MethodNotAllowed ¶
MethodNotAllowed returns a 405 Method Not Allowed response
func NoContentResponse ¶
NoContentResponse returns a 204 No Content response
func PaginateResults ¶
PaginateResults paginates a slice of results
func PaginatedResponse ¶
PaginatedResponse returns a standardized paginated response
func ParseContainerLabels ¶
ParseContainerLabels converts Docker API labels map to our JSONMap. Handles potential nil map from the API.
func ParseImageName ¶
ParseImageName parses a Docker image name string into its components. It wraps github.com/docker_test/distribution/reference.ParseNamed.
func ParseRepositoryTag ¶
ParseRepositoryTag splits a full image reference (e.g., "nginx:latest", "myregistry.com/myimage:v1") into repository name ("nginx", "myregistry.com/myimage") and tag ("latest", "v1"). It defaults the tag to "latest" if not specified.
func RateLimitMiddleware ¶
func RateLimitMiddleware(limiter *RateLimiter) gin.HandlerFunc
RateLimitMiddleware creates a middleware that limits request rates
func RecoveryMiddleware ¶
func RecoveryMiddleware() gin.HandlerFunc
RecoveryMiddleware creates a middleware that recovers from panics
func RedactSensitiveData ¶
RedactSensitiveData redacts sensitive data from a map
func RemoveNetwork ¶
func RemoveNetwork(ctx context.Context, cli DockerClient, networkIDOrName string, logger *logrus.Logger) error
RemoveNetwork removes a network if it exists.
func RemoveVolume ¶
func RemoveVolume(ctx context.Context, cli DockerClient, volumeIDOrName string, force bool, logger *logrus.Logger) error
RemoveVolume removes a volume if it exists.
func RequestIDMiddleware ¶
func RequestIDMiddleware() gin.HandlerFunc
RequestIDMiddleware creates a middleware that adds a request ID
func SanitizeDockerName ¶
SanitizeDockerName removes invalid characters from a Docker resource name.
func SanitizeHeaders ¶
SanitizeHeaders returns a map of headers with sensitive information masked
func SanitizeValue ¶
SanitizeValue sanitizes a value for logging
func SecureHeaders ¶
SecureHeaders adds security headers to the response
func ServiceUnavailable ¶
ServiceUnavailable returns a 503 Service Unavailable response
func SortNetworks ¶
SortNetworks sorts a slice of Network models. Placeholder implementation - returns the original slice. TODO: Implement actual sorting logic based on sortBy and sortOrder.
func StatusAccepted ¶
StatusAccepted returns a 202 Accepted response
func StringHasPrefix ¶
StringHasPrefix is a simple wrapper around strings.HasPrefix.
func StructToMap ¶
StructToMap converts a struct to a map using JSON tags
func SuccessResponse ¶
SuccessResponse returns a standardized success response
func TimeoutMiddleware ¶
func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc
TimeoutMiddleware creates a middleware that adds a timeout to requests
func TooManyRequests ¶
TooManyRequests returns a 429 Too Many Requests response
func Unauthorized ¶
Unauthorized returns a 401 Unauthorized response
func UnprocessableEntity ¶
UnprocessableEntity returns a 422 Unprocessable Entity response
func ValidateCSRFToken ¶
ValidateCSRFToken validates a CSRF token
func ValidateContainerName ¶
func ValidateContainerName(name string, options ...ValidationOptions) error
ValidateContainerName validates a container name.
func ValidateEmail ¶
func ValidateEmail(email string, options ...ValidationOptions) error
ValidateEmail validates an email address.
func ValidateFilename ¶
func ValidateFilename(filename string, options ...ValidationOptions) error
ValidateFilename validates a filename.
func ValidateIPAddress ¶
func ValidateIPAddress(ip string, options ...ValidationOptions) error
ValidateIPAddress validates an IP address.
func ValidateImageName ¶
func ValidateImageName(name string, options ...ValidationOptions) error
ValidateImageName validates a Docker image name.
func ValidateJSONInput ¶
func ValidateJSONInput(jsonStr string, maxDepth int, options ...ValidationOptions) error
ValidateJSONInput validates a JSON string.
func ValidateNetworkName ¶
func ValidateNetworkName(name string, options ...ValidationOptions) error
ValidateNetworkName validates a network name.
func ValidatePassword ¶
func ValidatePassword(password string, options ...ValidationOptions) error
ValidatePassword validates a password.
func ValidatePath ¶
func ValidatePath(path string, options ...ValidationOptions) error
ValidatePath validates a file path.
func ValidatePathHTTP ¶
ValidatePath validates a file path for security in HTTP context
func ValidatePortString ¶
ValidatePortString validates a port number as a string.
func ValidateRequestHeaders ¶
ValidateRequestHeaders checks if the request headers are valid
func ValidateURL ¶
func ValidateURL(rawURL string, allowedSchemes []string, options ...ValidationOptions) error
ValidateURL validates a URL.
func ValidateUsername ¶
func ValidateUsername(username string, options ...ValidationOptions) error
ValidateUsername validates a username.
func ValidateVolumeName ¶
func ValidateVolumeName(name string, options ...ValidationOptions) error
ValidateVolumeName validates a volume name.
func VerifyPassword ¶
VerifyPassword verifies a password against a hash.
Types ¶
type APIError ¶
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
Details string `json:"details,omitempty"`
}
APIError represents an API error
func FormatError ¶
FormatError formats an error for API responses
type DockerClient ¶
type DockerClient interface {
ContainerList(ctx context.Context, options container.ListOptions) ([]types.Container, error)
ContainerInspect(ctx context.Context, containerID string) (types.ContainerJSON, error)
ContainerLogs(ctx context.Context, container string, options container.LogsOptions) (io.ReadCloser, error)
ImageList(ctx context.Context, options image.ListOptions) ([]image.Summary, error)
ImageInspectWithRaw(ctx context.Context, imageID string) (types.ImageInspect, []byte, error)
ImagePull(ctx context.Context, ref string, options image.PullOptions) (io.ReadCloser, error)
NetworkList(ctx context.Context, options network.ListOptions) ([]network.Summary, error) // Use network.ListOptions and network.Summary
NetworkInspect(ctx context.Context, networkID string, options network.InspectOptions) (network.Inspect, error) // Use network.InspectOptions and network.Inspect
NetworkCreate(ctx context.Context, name string, options network.CreateOptions) (network.CreateResponse, error) // Use network.CreateOptions and network.CreateResponse
NetworkRemove(ctx context.Context, networkID string) error
VolumeList(ctx context.Context, filter filters.Args) (volume.ListResponse, error)
VolumeInspect(ctx context.Context, volumeID string) (volume.Volume, error)
VolumeCreate(ctx context.Context, options volume.CreateOptions) (volume.Volume, error)
VolumeRemove(ctx context.Context, volumeID string, force bool) error
Ping(ctx context.Context) (types.Ping, error)
}
DockerClient defines the interface for Docker client operations needed by utils
type HTTPClientConfig ¶
type HTTPClientConfig struct {
Timeout time.Duration
KeepAlive time.Duration
MaxIdleConns int
IdleConnTimeout time.Duration
TLSHandshakeTimeout time.Duration
ExpectContinueTimeout time.Duration
ResponseHeaderTimeout time.Duration
MaxResponseBodySize int64
Proxy func(*http.Request) (*url.URL, error)
TLSConfig *tls.Config
AllowedContentTypes []string
DisallowedHosts []string
}
HTTPClientConfig contains configuration for the HTTP client
func DefaultHTTPClientConfig ¶
func DefaultHTTPClientConfig() HTTPClientConfig
DefaultHTTPClientConfig returns the default HTTP client configuration
func SecureHTTPClientConfig ¶
func SecureHTTPClientConfig() HTTPClientConfig
SecureHTTPClientConfig returns a secure HTTP client configuration
type HTTPResponse ¶
HTTPResponse is a wrapper for HTTP responses
func HTTPRequest ¶
func HTTPRequest(ctx context.Context, method, urlString string, headers map[string]string, body io.Reader, config HTTPClientConfig) (*HTTPResponse, error)
HTTPRequest sends an HTTP request with security checks
type Meta ¶
type Meta struct {
Page int `json:"page,omitempty"`
PerPage int `json:"per_page,omitempty"`
TotalPages int `json:"total_pages,omitempty"`
Total int `json:"total,omitempty"`
Timestamp time.Time `json:"timestamp"`
RequestID string `json:"request_id,omitempty"`
Version string `json:"version,omitempty"`
}
Meta contains metadata for pagination responses
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter manages rate limiting for HTTP requests
func NewRateLimiter ¶
func NewRateLimiter(rps int, burst int) *RateLimiter
NewRateLimiter creates a new rate limiter
func (*RateLimiter) CleanupLimiters ¶
func (rl *RateLimiter) CleanupLimiters(maxAge time.Duration)
CleanupLimiters removes old limiters
func (*RateLimiter) GetLimiter ¶
func (rl *RateLimiter) GetLimiter(key string) *rate.Limiter
GetLimiter gets or creates a rate limiter for the given IP
type Response ¶
type Response struct {
Success bool `json:"success"`
Data interface{} `json:"data,omitempty"`
Error *APIError `json:"error,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
Response represents a standardized API response
type Throttle ¶
type Throttle struct {
// contains filtered or unexported fields
}
Throttle provides a mechanism to limit the rate of operations
func NewThrottle ¶
NewThrottle creates a new rate limiter with the specified limit per interval limit: maximum number of operations per interval interval: the time interval for the rate limit
type ValidationError ¶
type ValidationError struct {
Field string `json:"field"`
Code string `json:"code"`
Message string `json:"message"`
Value string `json:"value,omitempty"` // The invalid value (sanitized for sensitive fields)
}
ValidationError represents a validation error.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error implements the error interface.
type ValidationOptions ¶
type ValidationOptions struct {
// MaxLength is the maximum allowed length
MaxLength int
// MinLength is the minimum allowed length
MinLength int
// Required specifies if the value is required
Required bool
// StrictMode enables stricter validation rules
StrictMode bool
// AllowedValues is a list of allowed values
AllowedValues []string
// DisallowedValues is a list of disallowed values
DisallowedValues []string
// CustomValidation is a custom validation function
CustomValidation func(interface{}) error
// SanitizeOutput determines if output should be sanitized
SanitizeOutput bool
}
ValidationOptions contains options for validation.
type ValidationResult ¶
type ValidationResult struct {
Errors []*ValidationError `json:"errors"`
}
ValidationResult contains the result of a validation operation.
func NewValidationResult ¶
func NewValidationResult() *ValidationResult
NewValidationResult creates a new ValidationResult.
func ValidateContainerSecurityOptions ¶
func ValidateContainerSecurityOptions(container types.Container) *ValidationResult
Validate container security options using types.Container
func ValidateCredentials ¶
func ValidateCredentials(username, password string, options ...ValidationOptions) *ValidationResult
ValidateCredentials validates username and password credentials
func ValidateSecurityOpts ¶
func ValidateSecurityOpts(opts []string) *ValidationResult
ValidateSecurityOpts validates Docker security options.
func ValidateStruct ¶
func ValidateStruct(s interface{}) *ValidationResult
ValidateStruct validates a struct using validator tags
func (*ValidationResult) AddError ¶
func (vr *ValidationResult) AddError(field, code, message string, value ...interface{})
AddError adds an error to the validation result.
func (*ValidationResult) ErrorMessages ¶
func (vr *ValidationResult) ErrorMessages() []string
ErrorMessages returns all error messages.
func (*ValidationResult) ErrorsByField ¶
func (vr *ValidationResult) ErrorsByField() map[string]string
ErrorsByField returns a map of field names to error messages.
func (*ValidationResult) First ¶
func (vr *ValidationResult) First() *ValidationError
First returns the first error or nil if there are no errors.
func (*ValidationResult) GetErrors ¶
func (vr *ValidationResult) GetErrors() []*ValidationError
GetErrors returns all validation errors.
func (*ValidationResult) IsValid ¶
func (vr *ValidationResult) IsValid() bool
IsValid returns true if the validation passed.
func (*ValidationResult) MergeResults ¶
func (vr *ValidationResult) MergeResults(other *ValidationResult)
MergeResults merges the errors from another ValidationResult into this one.
func (*ValidationResult) ToJSON ¶
func (vr *ValidationResult) ToJSON() (string, error)
ToJSON returns the validation result as a JSON string.