LoginSignup
1
2

More than 5 years have passed since last update.

[Go] gorilla/schema でデコードする際の必須フィールド指定

Posted at

https://github.com/gorilla/schema でGoのstructへデコードする際に、
必須のフィールドを持たせてバリデーションしたい場合。

tl;dr

タグオプションの required を使う。

type Person struct {
    Mail        string `schema:"mail,required"`
    PhoneNumber string `schema:"phone_number"`
}

example

例として、URLパラメータをデコードしてみる。

package main

import (
    "fmt"
    "net/url"

    "github.com/gorilla/schema"
)

type Person struct {
    Mail        string `schema:"mail,required"`
    PhoneNumber string `schema:"phone_number"`
}

func main() {
    q1 := url.Values{}
    q1.Add("mail", "hoge@example.com")

    p1 := &Person{}
    d1 := schema.NewDecoder()
    if err := d1.Decode(p1, q1); err == nil {
        fmt.Printf("1. error does not occur.\n")
    }

    q2 := url.Values{}
    q2.Add("phone_number", "11122223333")

    p2 := &Person{}
    d2 := schema.NewDecoder()
    if err := d2.Decode(p2, q2); err != nil {
        fmt.Printf("2. error occurred.\n%v", err)
    }
}
$ go run main.go
1. error does not occur.
2. error occurred.
mail is empty

ドキュメント では触れられてないが、
ソースコードをみれば、requiredオプションのチェックがあることが分かる。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2