github.com/blend/go-sdk@v1.20220411.3/examples/validate/main.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package main
     9  
    10  import (
    11  	"fmt"
    12  	"time"
    13  
    14  	"github.com/blend/go-sdk/ref"
    15  	"github.com/blend/go-sdk/uuid"
    16  
    17  	// if you're feeling evil.
    18  	joi "github.com/blend/go-sdk/validate"
    19  )
    20  
    21  // Validated is a validated object.
    22  type Validated struct {
    23  	ID       uuid.UUID
    24  	Name     string
    25  	Count    int
    26  	Created  time.Time
    27  	Optional *string
    28  }
    29  
    30  // Validate implements validated.
    31  func (v Validated) Validate() error {
    32  	return joi.ReturnFirst(
    33  		joi.Any(v.ID).NotNil(),
    34  		joi.String(&v.Name).Required(),
    35  		joi.String(&v.Name).Matches("foo$"),
    36  		joi.Int(&v.Count).Between(0, 99),
    37  		joi.Any(&v.Count).NotEquals(81),
    38  		joi.Time(&v.Created).BeforeNowUTC(),
    39  		joi.WhenElse(
    40  			func() bool { return v.ID != nil && v.ID.IsV4() },
    41  			joi.String(v.Optional).IsURI(), // not sure why
    42  			joi.String(v.Optional).IsIP(),  // still not sure why
    43  		),
    44  	)
    45  }
    46  
    47  func main() {
    48  	objects := []Validated{
    49  		{ID: uuid.V4(), Name: "foo", Count: 55, Created: time.Now().UTC(), Optional: ref.String("https://google.com")},
    50  		{ID: uuid.Zero, Name: "foo", Count: 55, Created: time.Now().UTC(), Optional: ref.String("127.0.0.1")},
    51  	}
    52  
    53  	for index, obj := range objects {
    54  		if err := obj.Validate(); err != nil {
    55  			fmt.Printf("object %d fails validation: %v\n", index, joi.ErrFormat(err))
    56  		}
    57  	}
    58  }