Struct Tags For JSON And Validation

Drive serialization and validation from one struct tag line so the wire format and the rules are declared in the same place.

GoData Integrity

Code

gosnippet
39 lines
package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

type Signup struct {
	Email    string `json:"email" validate:"required,email"`
	Password string `json:"password" validate:"min=8"`
	Nickname string `json:"nickname,omitempty"`
}

func validate(s Signup) []string {
	var problems []string
	if !strings.Contains(s.Email, "@") {
		problems = append(problems, "email must contain @")
	}
	if len(s.Password) < 8 {
		problems = append(problems, "password must be at least 8 chars")
	}
	return problems
}

func main() {
	raw := []byte(`{"email":"a@b.c","password":"s3cret-pass","nickname":"ada"}`)
	var s Signup
	if err := json.Unmarshal(raw, &s); err != nil {
		fmt.Println("decode failed:", err)
		return
	}
	fmt.Printf("decoded: %+v\n", s)
	fmt.Println("problems:", validate(s))

	// omitempty:零值字段不出现在输出里
	out, _ := json.Marshal(Signup{Email: "x@y.z", Password: "longenough"})
	fmt.Println(string(out))
}

Following the data

Struct Tags For JSON And Validation keeps everything in the functions validate and main.

Nothing falls through silently — 1 checkpoint test err != nil on the way through.

Putting it to use

The primary signature is func validate(s Signup) []string

Running the file prints labeled results such as decode failed:, decoded:, problems: — each operation’s effect is visible in the output.

The demo flow inside main is validate — run the file to see it end to end.

Core lines

func validate(s Signup) []string {
var problems []string
if !strings.Contains(s.Email, "@") {
problems = append(problems, "email must contain @")
}
if len(s.Password) < 8 {
problems = append(problems, "password must be at least 8 chars")
}
return problems
}

Interactive Tools for This Topic

FAQ

What does Struct Tags For JSON And Validation print when run?
Running the file directly is enough — expect labeled output lines such as `decode failed:`, `decoded:`, `problems:`.