package jsonschemaimport (gourl)// Format defined specific format.typeFormatstruct {// Name of format. Name string// Validate checks if given value is of this format. Validate func(v any) error}var formats = map[string]*Format{"json-pointer": {"json-pointer", validateJSONPointer},"relative-json-pointer": {"relative-json-pointer", validateRelativeJSONPointer},"uuid": {"uuid", validateUUID},"duration": {"duration", validateDuration},"period": {"period", validatePeriod},"ipv4": {"ipv4", validateIPV4},"ipv6": {"ipv6", validateIPV6},"hostname": {"hostname", validateHostname},"email": {"email", validateEmail},"date": {"date", validateDate},"time": {"time", validateTime},"date-time": {"date-time", validateDateTime},"uri": {"uri", validateURI},"iri": {"iri", validateURI},"uri-reference": {"uri-reference", validateURIReference},"iri-reference": {"iri-reference", validateURIReference},"uri-template": {"uri-template", validateURITemplate},"semver": {"semver", validateSemver},}// see https://www.rfc-editor.org/rfc/rfc6901#section-3func validateJSONPointer( any) error { , := .(string)if ! {returnnil }if == "" {returnnil }if !strings.HasPrefix(, "/") {returnLocalizableError("not starting with /") }for , := rangestrings.Split(, "/")[1:] { := falsefor , := range {if { = falseif != '0' && != '1' {returnLocalizableError("~ must be followed by 0 or 1") }continue }if == '~' { = truecontinue }switch {case >= '\x00' && <= '\x2E':case >= '\x30' && <= '\x7D':case >= '\x7F' && <= '\U0010FFFF':default:returnLocalizableError("invalid character %q", ) } }if {returnLocalizableError("~ must be followed by 0 or 1") } }returnnil}// see https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01#section-3func validateRelativeJSONPointer( any) error { , := .(string)if ! {returnnil }// start with non-negative-integer := 0for , := range {if >= '0' && <= '9' { ++ } else {break } }if == 0 {returnLocalizableError("must start with non-negative integer") }if > 1 && strings.HasPrefix(, "0") {returnLocalizableError("starts with zero") } = [:]// followed by either json-pointer or '#'if == "#" {returnnil }returnvalidateJSONPointer()}// see https://datatracker.ietf.org/doc/html/rfc4122#page-4func validateUUID( any) error { , := .(string)if ! {returnnil } := []int{8, 4, 4, 4, 12} := strings.Split(, "-")iflen() != len() {returnLocalizableError("must have %d elements", len()) }for , := range {iflen() != [] {returnLocalizableError("element %d must be %d characters long", +1, []) }for , := range {switch {case >= '0' && <= '9':case >= 'a' && <= 'f':case >= 'A' && <= 'F':default:returnLocalizableError("non-hex character %q", ) } } }returnnil}// see https://datatracker.ietf.org/doc/html/rfc3339#appendix-Afunc validateDuration( any) error { , := .(string)if ! {returnnil }// must start with 'P' , = strings.CutPrefix(, "P")if ! {returnLocalizableError("must start with P") }if == "" {returnLocalizableError("nothing after P") }// dur-weekif , := strings.CutSuffix(, "W"); {if == "" {returnLocalizableError("no number in week") }for , := range {if < '0' || > '9' {returnLocalizableError("invalid week") } }returnnil } := []string{"YMD", "HMS"}for , := rangestrings.Split(, "T") {if != 0 && == "" {returnLocalizableError("no time elements") }if >= len() {returnLocalizableError("more than one T") } := []for != "" { := 0for , := range {if >= '0' && <= '9' { ++ } else {break } }if == 0 {returnLocalizableError("missing number") } = [:]if == "" {returnLocalizableError("missing unit") } := [0] := strings.IndexByte(, )if == -1 {ifstrings.IndexByte([], ) != -1 {returnLocalizableError("unit %q out of order", ) }returnLocalizableError("invalid unit %q", ) } = [+1:] = [1:] } }returnnil}func validateIPV4( any) error { , := .(string)if ! {returnnil } := strings.Split(, ".")iflen() != 4 {returnLocalizableError("expected four decimals") }for , := range {iflen() > 1 && [0] == '0' {returnLocalizableError("leading zeros") } , := strconv.Atoi()if != nil {return }if < 0 || > 255 {returnLocalizableError("decimal must be between 0 and 255") } }returnnil}func validateIPV6( any) error { , := .(string)if ! {returnnil }if !strings.Contains(, ":") {returnLocalizableError("missing colon") } , := netip.ParseAddr()if != nil {return }if .Zone() != "" {returnLocalizableError("zone id is not a part of ipv6 address") }returnnil}// see https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_namesfunc validateHostname( any) error { , := .(string)if ! {returnnil }// entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters = strings.TrimSuffix(, ".")iflen() > 253 {returnLocalizableError("more than 253 characters long") }// Hostnames are composed of series of labels concatenated with dots, as are all domain namesfor , := rangestrings.Split(, ".") {// Each label must be from 1 to 63 characters longiflen() < 1 || len() > 63 {returnLocalizableError("label must be 1 to 63 characters long") }// labels must not start or end with a hyphenifstrings.HasPrefix(, "-") {returnLocalizableError("label starts with hyphen") }ifstrings.HasSuffix(, "-") {returnLocalizableError("label ends with hyphen") }// labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), // the digits '0' through '9', and the hyphen ('-')for , := range {switch {case >= 'a' && <= 'z':case >= 'A' && <= 'Z':case >= '0' && <= '9':case == '-':default:returnLocalizableError("invalid character %q", ) } } }returnnil}// see https://en.wikipedia.org/wiki/Email_addressfunc validateEmail( any) error { , := .(string)if ! {returnnil }// entire email address to be no more than 254 characters longiflen() > 254 {returnLocalizableError("more than 255 characters long") }// email address is generally recognized as having two parts joined with an at-sign := strings.LastIndexByte(, '@')if == -1 {returnLocalizableError("missing @") } , := [:], [+1:]// local part may be up to 64 characters longiflen() > 64 {returnLocalizableError("local part more than 64 characters long") }iflen() > 1 && strings.HasPrefix(, `"`) && strings.HasSuffix(, `"`) {// quoted := [1 : len()-1]ifstrings.IndexByte(, '\\') != -1 || strings.IndexByte(, '"') != -1 {returnLocalizableError("backslash and quote are not allowed within quoted local part") } } else {// unquotedifstrings.HasPrefix(, ".") {returnLocalizableError("starts with dot") }ifstrings.HasSuffix(, ".") {returnLocalizableError("ends with dot") }// consecutive dots not allowedifstrings.Contains(, "..") {returnLocalizableError("consecutive dots") }// check allowed charsfor , := range {switch {case >= 'a' && <= 'z':case >= 'A' && <= 'Z':case >= '0' && <= '9':casestrings.ContainsRune(".!#$%&'*+-/=?^_`{|}~", ):default:returnLocalizableError("invalid character %q", ) } } }// domain if enclosed in brackets, must match an IP addressifstrings.HasPrefix(, "[") && strings.HasSuffix(, "]") { = [1 : len()-1]if , := strings.CutPrefix(, "IPv6:"); {if := validateIPV6(); != nil {returnLocalizableError("invalid ipv6 address: %v", ) }returnnil }if := validateIPV4(); != nil {returnLocalizableError("invalid ipv4 address: %v", ) }returnnil }// domain must match the requirements for a hostnameif := validateHostname(); != nil {returnLocalizableError("invalid domain: %v", ) }returnnil}// see see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6func validateDate( any) error { , := .(string)if ! {returnnil } , := time.Parse("2006-01-02", )return}// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6// NOTE: golang time package does not support leap seconds.func validateTime( any) error { , := .(string)if ! {returnnil }// min: hh:mm:ssZiflen() < 9 {returnLocalizableError("less than 9 characters long") }if [2] != ':' || [5] != ':' {returnLocalizableError("missing colon in correct place") }// parse hh:mm:ssvar []intfor , := rangestrings.SplitN([:8], ":", 3) { , := strconv.Atoi()if != nil {returnLocalizableError("invalid hour/min/sec") }if < 0 {returnLocalizableError("non-positive hour/min/sec") } = append(, ) }iflen() != 3 {returnLocalizableError("missing hour/min/sec") } , , := [0], [1], [2]if > 23 || > 59 || > 60 {returnLocalizableError("hour/min/sec out of range") } = [8:]// parse sec-frac if presentif , := strings.CutPrefix(, "."); { := 0for , := range {if >= '0' && <= '9' { ++ } else {break } }if == 0 {returnLocalizableError("no digits in second fraction") } = [:] }if != "z" && != "Z" {// parse time-numoffsetiflen() != 6 {returnLocalizableError("offset must be 6 characters long") }varintswitch [0] {case'+': = -1case'-': = +1default:returnLocalizableError("offset must begin with plus/minus") } = [1:]if [2] != ':' {returnLocalizableError("missing colon in offset in correct place") }var []intfor , := rangestrings.SplitN(, ":", 2) { , := strconv.Atoi()if != nil {returnLocalizableError("invalid hour/min in offset") }if < 0 {returnLocalizableError("non-positive hour/min in offset") } = append(, ) } , := [0], [1]if > 23 || > 59 {returnLocalizableError("hour/min in offset out of range") }// apply timezone := (*60 + ) + *(*60+)if < 0 { += 24 * 60 } , = /60, %60 }// check leap secondif >= 60 && ( != 23 || != 59) {returnLocalizableError("invalid leap second") }returnnil}// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6func validateDateTime( any) error { , := .(string)if ! {returnnil }// min: yyyy-mm-ddThh:mm:ssZiflen() < 20 {returnLocalizableError("less than 20 characters long") }if [10] != 't' && [10] != 'T' {returnLocalizableError("11th character must be t or T") }if := validateDate([:10]); != nil {returnLocalizableError("invalid date element: %v", ) }if := validateTime([11:]); != nil {returnLocalizableError("invalid time element: %v", ) }returnnil}func parseURL( string) (*gourl.URL, error) { , := gourl.Parse()if != nil {returnnil, }// gourl does not validate ipv6 host address := .Hostname()ifstrings.Contains(, ":") {if !strings.Contains(.Host, "[") || !strings.Contains(.Host, "]") {returnnil, LocalizableError("ipv6 address not enclosed in brackets") }if := validateIPV6(); != nil {returnnil, LocalizableError("invalid ipv6 address: %v", ) } }return , nil}func validateURI( any) error { , := .(string)if ! {returnnil } , := parseURL()if != nil {return }if !.IsAbs() {returnLocalizableError("relative url") }returnnil}func validateURIReference( any) error { , := .(string)if ! {returnnil }ifstrings.Contains(, `\`) {returnLocalizableError(`contains \`) } , := parseURL()return}func validateURITemplate( any) error { , := .(string)if ! {returnnil } , := parseURL()if != nil {return }for , := rangestrings.Split(.RawPath, "/") { , = decode()if != nil {returnLocalizableError("percent decode failed: %v", ) } := truefor , := range {varboolswitch {case'{': = truecase'}': = falsedefault:continue }if != {returnLocalizableError("nested curly braces") } = ! }if ! {returnLocalizableError("no matching closing brace") } }returnnil}func validatePeriod( any) error { , := .(string)if ! {returnnil } := strings.IndexByte(, '/')if == -1 {returnLocalizableError("missing slash") } , := [:], [+1:]ifstrings.HasPrefix(, "P") {if := validateDuration(); != nil {returnLocalizableError("invalid start duration: %v", ) }if := validateDateTime(); != nil {returnLocalizableError("invalid end date-time: %v", ) } } else {if := validateDateTime(); != nil {returnLocalizableError("invalid start date-time: %v", ) }ifstrings.HasPrefix(, "P") {if := validateDuration(); != nil {returnLocalizableError("invalid end duration: %v", ) } } elseif := validateDateTime(); != nil {returnLocalizableError("invalid end date-time: %v", ) } }returnnil}// see https://semver.org/#backusnaur-form-grammar-for-valid-semver-versionsfunc validateSemver( any) error { , := .(string)if ! {returnnil }// build --if := strings.IndexByte(, '+'); != -1 { := [+1:]if == "" {returnLocalizableError("build is empty") }for , := rangestrings.Split(, ".") {if == "" {returnLocalizableError("build identifier is empty") }for , := range {switch {case >= '0' && <= '9':case ( >= 'a' && <= 'z') || ( >= 'A' && <= 'Z') || == '-':default:returnLocalizableError("invalid character %q in build identifier", ) } } } = [:] }// pre-release --if := strings.IndexByte(, '-'); != -1 { := [+1:]for , := rangestrings.Split(, ".") {if == "" {returnLocalizableError("pre-release identifier is empty") } := truefor , := range {switch {case >= '0' && <= '9':case ( >= 'a' && <= 'z') || ( >= 'A' && <= 'Z') || == '-': = falsedefault:returnLocalizableError("invalid character %q in pre-release identifier", ) } }if && len() > 1 && [0] == '0' {returnLocalizableError("pre-release numeric identifier starts with zero") } } = [:] }// versionCore -- := strings.Split(, ".")iflen() != 3 {returnLocalizableError("versionCore must have 3 numbers separated by dot") } := []string{"major", "minor", "patch"}for , := range {if == "" {returnLocalizableError("%s is empty", []) }iflen() > 1 && [0] == '0' {returnLocalizableError("%s starts with zero", []) }for , := range {if < '0' || > '9' {returnLocalizableError("%s contains non-digit", []) } } }returnnil}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.