コード例 #1
0
ファイル: validation.go プロジェクト: konstantin-dzreev/goa
// ValidateFormat validates a string against a standard format.
// It returns nil if the string conforms to the format, an error otherwise.
// The format specification follows the json schema draft 4 validation extension.
// see http://json-schema.org/latest/json-schema-validation.html#anchor105
// Supported formats are:
//
//     - "date-time": RFC3339 date time value
//     - "email": RFC5322 email address
//     - "hostname": RFC1035 Internet host name
//     - "ipv4", "ipv6", "ip": RFC2673 and RFC2373 IP address values
//     - "uri": RFC3986 URI value
//     - "mac": IEEE 802 MAC-48, EUI-48 or EUI-64 MAC address value
//     - "cidr": RFC4632 and RFC4291 CIDR notation IP address value
//     - "regexp": Regular expression syntax accepted by RE2
func ValidateFormat(f Format, val string) error {
	var err error
	switch f {
	case FormatDateTime:
		_, err = time.Parse(time.RFC3339, val)
	case FormatUUID:
		_, err = uuid.FromString(val)
	case FormatEmail:
		_, err = mail.ParseAddress(val)
	case FormatHostname:
		if !hostnameRegex.MatchString(val) {
			err = fmt.Errorf("hostname value '%s' does not match %s",
				val, hostnameRegex.String())
		}
	case FormatIPv4, FormatIPv6, FormatIP:
		ip := net.ParseIP(val)
		if ip == nil {
			err = fmt.Errorf("\"%s\" is an invalid %s value", val, f)
		}
		if f == FormatIPv4 {
			if !ipv4Regex.MatchString(val) {
				err = fmt.Errorf("\"%s\" is an invalid ipv4 value", val)
			}
		}
		if f == FormatIPv6 {
			if ipv4Regex.MatchString(val) {
				err = fmt.Errorf("\"%s\" is an invalid ipv6 value", val)
			}
		}
	case FormatURI:
		_, err = url.ParseRequestURI(val)
	case FormatMAC:
		_, err = net.ParseMAC(val)
	case FormatCIDR:
		_, _, err = net.ParseCIDR(val)
	case FormatRegexp:
		_, err = regexp.Compile(val)
	default:
		return fmt.Errorf("unknown format %#v", f)
	}
	if err != nil {
		go IncrCounter([]string{"goa", "validation", "error", string(f)}, 1.0)
		return fmt.Errorf("invalid %s value, %s", f, err)
	}
	return nil
}
コード例 #2
0
import (
	"bytes"
	"encoding/json"
	"fmt"

	"github.com/goadesign/goa/uuid"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("JsonEncoding", func() {

	Describe("handle goa/uuid/UUID", func() {
		name := "Test"
		id, _ := uuid.FromString("c0586f01-87b5-462b-a673-3b2dcf619091")

		type Payload struct {
			ID   uuid.UUID
			Name string
		}

		It("encode", func() {
			data := Payload{
				id,
				name,
			}

			var b bytes.Buffer
			encoder := json.NewEncoder(&b)
			encoder.Encode(data)