Skip to content

Instantly share code, notes, and snippets.

@apg
Created April 5, 2012 11:44
Show Gist options
  • Save apg/2310175 to your computer and use it in GitHub Desktop.
Save apg/2310175 to your computer and use it in GitHub Desktop.
Some playing around with go validation ideas.
package main
import (
"errors"
"fmt"
)
type BaseField interface {
NameOf() string
IsOptional() bool
}
type Foo struct {
Name string
Optional bool
}
type Bar struct {
Name string
Optional bool
Maximum int
}
func BaseValid(f BaseField, inp string) (out string, err error) {
if f.IsOptional() && inp == "" {
return "", nil
} else if inp == "" {
return "", errors.New(fmt.Sprintf("%v is not optional", f.NameOf()))
}
return inp, nil
}
func (f *Bar) Valid(inp string) (out string, err error) {
out, err = BaseValid(f, inp)
return
}
func (f *Bar) NameOf() string {
return f.Name
}
func (f *Bar) IsOptional() bool {
return f.Optional
}
func main() {
f := Bar { Name: "Foob", Optional: false }
o, e := f.Valid("red")
fmt.Printf("out: %v, err: %v\n", o, e)
o, e = f.Valid("")
fmt.Printf("out: %v, err: %v\n", o, e)
f.Optional = true
o, e = f.Valid("")
fmt.Printf("out: %v, err: %v\n", o, e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment