Closed
Description
Problem statement
Hi, All,
Today I ran into an issue that I have a definition which has a Hostname, and hostname has a format of hostname
using strfmt
:
definitions:
ContainerConfig:
type: "object"
description: "Configuration for a container that is portable between hosts"
properties:
Hostname:
description: "The hostname to use for the container, as a valid RFC 1123 hostname."
type: "string"
format: hostname
When when I generate container_config.go
, I did not find any validation code for field Hostname:
// Code generated by go-swagger; DO NOT EDIT.
package types
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
strfmt "github.com/go-openapi/strfmt"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
)
// ContainerConfig Configuration for a container that is portable between hosts
// swagger:model ContainerConfig
type ContainerConfig struct {
// The hostname to use for the container, as a valid RFC 1123 hostname.
Hostname strfmt.Hostname `json:"Hostname,omitempty"`
}
// Validate validates this container config
func (m *ContainerConfig) Validate(formats strfmt.Registry) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// MarshalBinary interface implementation
func (m *ContainerConfig) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *ContainerConfig) UnmarshalBinary(b []byte) error {
var res ContainerConfig
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}
So why does it not validate Hostname if this is a not required field?
And I tested that if I add Hostname as required, validation code will generated:
// Validate validates this container config
func (m *ContainerConfig) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateHostname(formats); err != nil {
// prop
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *ContainerConfig) validateHostname(formats strfmt.Registry) error {
if err := validate.Required("Hostname", "body", m.Hostname); err != nil {
return err
}
if err := validate.FormatOf("Hostname", "body", "hostname", m.Hostname.String(), formats); err != nil {
return err
}
return nil
}
And if I add a pattern for this not required field, validation code will be generated. Is adding pattern the only way to validate format of a not required field?
/cc @CodeJuan
Swagger specification
Steps to reproduce
Environment
swagger version:
$ swagger version
dev
go version: go version go1.9.1 darwin/amd64
OS: