モデルのバインディングと検証

リクエストボディを型にバインドするには、モデルバインディングを使用します。現在、JSON、XML、YAML、および標準フォーム値(foo=bar&boo=baz)のバインディングをサポートしています。

Gin はバリデーションに go-playground/validator/v10 を使用します。タグの使用法に関する完全なドキュメントはこちらをご覧ください。

バインドしたいすべてのフィールドに、対応するバインディングタグを設定する必要があることに注意してください。たとえば、JSON からバインドする場合、json:"fieldname" を設定します。

また、Gin はバインディング用に2種類のメソッドを提供しています。

  • 種類 - 必須バインド
    • メソッド - BindBindJSONBindXMLBindQueryBindYAML
    • 動作 - これらのメソッドは内部で MustBindWith を使用します。バインディングエラーが発生した場合、リクエストは c.AbortWithError(400, err).SetType(ErrorTypeBind) で中止されます。これにより、レスポンスステータスコードが 400 に設定され、Content-Type ヘッダーが text/plain; charset=utf-8 に設定されます。この後にレスポンスコードを設定しようとすると、警告 [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422 が発生することに注意してください。動作をより詳細に制御したい場合は、ShouldBind に相当するメソッドの使用を検討してください。
  • 種類 - 条件付きバインド
    • メソッド - ShouldBindShouldBindJSONShouldBindXMLShouldBindQueryShouldBindYAML
    • 動作 - これらのメソッドは内部で ShouldBindWith を使用します。バインディングエラーが発生した場合、エラーが返され、リクエストとエラーを適切に処理するのは開発者の責任です。

Bind メソッドを使用する場合、Gin は Content-Type ヘッダーに基づいてバインダーを推測しようとします。バインドする内容がわかっている場合は、MustBindWith または ShouldBindWith を使用できます。

特定のフィールドが必須であることを指定することもできます。フィールドが binding:"required" で修飾され、バインディング時に空の値を持つ場合、エラーが返されます。

// Binding from JSON
type Login struct {
	User     string `form:"user" json:"user" xml:"user"  binding:"required"`
	Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

func main() {
	router := gin.Default()

	// Example for binding JSON ({"user": "manu", "password": "123"})
	router.POST("/loginJSON", func(c *gin.Context) {
		var json Login
		if err := c.ShouldBindJSON(&json); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		
		if json.User != "manu" || json.Password != "123" {
			c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			return
		} 
		
		c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
	})

	// Example for binding XML (
	//	<?xml version="1.0" encoding="UTF-8"?>
	//	<root>
	//		<user>manu</user>
	//		<password>123</password>
	//	</root>)
	router.POST("/loginXML", func(c *gin.Context) {
		var xml Login
		if err := c.ShouldBindXML(&xml); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		
		if xml.User != "manu" || xml.Password != "123" {
			c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			return
		} 
		
		c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
	})

	// Example for binding a HTML form (user=manu&password=123)
	router.POST("/loginForm", func(c *gin.Context) {
		var form Login
		// This will infer what binder to use depending on the content-type header.
		if err := c.ShouldBind(&form); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		
		if form.User != "manu" || form.Password != "123" {
			c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			return
		} 
		
		c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
	})

	// Listen and serve on 0.0.0.0:8080
	router.Run(":8080")
}

リクエスト例

$ curl -v -X POST \
  http://localhost:8080/loginJSON \
  -H 'content-type: application/json' \
  -d '{ "user": "manu" }'
> POST /loginJSON HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.51.0
> Accept: */*
> content-type: application/json
> Content-Length: 18
>
* upload completely sent off: 18 out of 18 bytes
< HTTP/1.1 400 Bad Request
< Content-Type: application/json; charset=utf-8
< Date: Fri, 04 Aug 2017 03:51:31 GMT
< Content-Length: 100
<
{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}

バリデーションをスキップ

上記の curl コマンドを使用して上記の例を実行すると、エラーが返されます。これは、例では Passwordbinding:"required" を使用しているためです。Passwordbinding:"-" を使用すると、上記の例を再度実行してもエラーは返されません。

最終更新日:2024年5月10日: GitHub action workflows の更新 (#276) (4371021)