Skip to content

Commit

Permalink
up
Browse files Browse the repository at this point in the history
  • Loading branch information
gqcn committed Nov 26, 2024
1 parent 416d3a9 commit 663e632
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 35 deletions.
Original file line number Diff line number Diff line change
@@ -1,52 +1,52 @@
---
slug: '/docs/web/request-struct-converting'
title: 'Request - Object Conversion'
title: 'Request - Parameter Binding'
sidebar_position: 1
hide_title: true
keywords: [Object conversion, Parameter mapping, GoFrame framework, Request parsing, Struct conversion, Custom mapping, Data validation, Route registration, JSON response, Golang]
description: "This document provides a detailed overview of how to handle object conversion for request input when using the GoFrame framework. By defining inputs and outputs as struct objects, it facilitates structured parameter maintenance. It introduces the default and custom parameter mapping rules and how to conveniently perform object conversion and data validation using the Parse method of the Request object."
keywords: [parameter binding, request parsing, struct binding, GoFrame framework, parameter mapping, custom binding, data validation, route registration, JSON response, Go language]
description: 'This document details how to handle request parameter binding in the GoFrame framework. By binding request parameters to struct objects, it facilitates structured parameter handling. The document introduces default and custom parameter binding rules, and how to perform convenient parameter binding and data validation through the Parse method of the Request object.'
---

## Object Conversion
## Parameter Binding

Object conversion is very common in request processing. We recommend defining inputs and outputs as `struct` objects to facilitate structured parameter input and output maintenance. The `GoFrame` framework supports very convenient object conversion, allowing client-submitted parameters such as `Query` parameters, form parameters, content parameters, `JSON/XML`, etc., to be easily converted to designated `struct` objects. It also supports maintaining the mapping relationship between submitted parameters and `struct` attributes.
Parameter binding is a common requirement in request processing. We recommend binding request parameters to `struct` objects for structured parameter handling. The `GoFrame` framework provides convenient parameter binding capabilities, supporting binding of client-submitted parameters such as `Query` parameters, form parameters, content parameters, `JSON/XML`, etc., to specified `struct` objects, and supports maintaining the mapping relationship between submitted parameters and `struct` properties.

The object conversion method uses the `Parse` method or `Get*Struct` methods of the `Request` object. For specific method definitions, please refer to the API documentation: [https://pkg.go.dev/github.com/gogf/gf/v2/net/ghttp#Request](https://pkg.go.dev/github.com/gogf/gf/v2/net/ghttp#Request)
Parameter binding methods use the `Parse` method or `Get*Struct` methods of the `Request` object. For specific method definitions, please refer to the API documentation: [https://pkg.go.dev/github.com/gogf/gf/v2/net/ghttp#Request](https://pkg.go.dev/github.com/gogf/gf/v2/net/ghttp#Request)

## Parameter Mapping

### Default Rules

If the client's submitted parameters need to map to the server-defined `struct` attributes, the default mapping relationship can be used, which is very convenient. The default conversion rules are as follows:
When binding client-submitted parameters to server-defined `struct` properties, you can use the default mapping rules, which is very convenient. The default binding rules are as follows:

1. Attributes in the `struct` that need matching must be **public attributes** (capitalized first letter).
2. Parameter names will automatically match with `struct` attributes in a **case-insensitive** manner and **ignore `-/ /space` symbols**.
3. If matching is successful, the key-value is assigned to the attribute; if not, the key-value is ignored.
1. Properties in the `struct` that need to be bound must be **`public properties`** (first letter capitalized).
2. Parameter names will automatically match with `struct` properties in a **`case-insensitive`** manner and **ignoring `-/_/space` symbols**.
3. If the match is successful, the parameter value will be bound to the property; if it cannot be matched, the parameter will be ignored.

Here are some matching examples:

```html
Map Key Struct Attribute Match
name Name match
Email Email match
nickname NickName match
NICKNAME NickName match
Nick-Name NickName match
nick_name NickName match
nick name NickName match
NickName Nick_Name match
Nick-name Nick_Name match
nick_name Nick_Name match
nick name Nick_Name match
map key name struct property Match?
name Name match
Email Email match
nickname NickName match
NICKNAME NickName match
Nick-Name NickName match
nick_name NickName match
nick name NickName match
NickName Nick_Name match
Nick-name Nick_Name match
nick_name Nick_Name match
nick name Nick_Name match
```

Since object conversion at the underlying layer uses the `gconv` module, it also supports the `c/gconv/json` tags. More detailed rules can be found in the section [Type Conversion - Struct](../../核心组件/类型转换/类型转换-Struct转换.md).
Since the underlying parameter binding implementation uses the `gconv` module, it also supports `c/gconv/json` tags. For more detailed rules, please refer to the [Type Conversion - Struct](../../核心组件/类型转换/类型转换-Struct转换.md) chapter.

### Custom Rules

Please use custom mapping rules in business scenarios where there is a significant difference between object properties and parameter names; otherwise, please use the default parameter mapping rules. A large number of custom rules tags can increase code maintenance costs.
Please use custom binding rules in business scenarios where struct properties and parameter names differ significantly; otherwise, use the default parameter binding rules. This is because a large number of custom rule tags will increase code maintenance costs.

Custom parameter mapping rules can be implemented by binding a `tag` to `struct` attributes. The tag name can be `p/param/params`. For example:
Custom parameter binding rules can be implemented by binding `tags` to `struct` properties. The `tag` names can be `p/param/params`. For example:

```go
type User struct{
Expand All @@ -57,13 +57,13 @@ type User struct{
}
```

In which we use the `p` tag to specify the parameter name bound to the attribute. The `password1` parameter will map to the `Pass1` attribute, and `password2` will map to the `Pass2` attribute. Other attributes use default conversion rules without needing to set a `tag`.
Here we use the `p` tag to specify which parameter should bind to which property. The `password1` parameter will bind to the `Pass1` property, and `password2` will bind to the `Pass2` property. Other properties can use the default binding rules without setting `tags`.

## `Parse` Conversion
## `Parse` Binding

We can also use the `Parse` method to achieve `struct` conversion. This method is a convenience method that will automatically perform conversion and data validation internally, but if the `struct` does not have a bound validation `tag`, the validation logic will not be executed.
We can use the `Parse` method to implement parameter binding to structs. This method is a convenient method that will automatically perform binding and data validation internally, but if there are no validation `tags` bound in the `struct`, validation logic will not be executed.
:::warning
Starting from `GoFrame v2`, we recommend using a structured approach to define route methods for more convenient management of input and output data structures and instances. For details, please refer to: [Standard Router](../路由管理/路由管理-路由注册/路由注册-规范路由/路由注册-规范路由.md)
Starting from `GoFrame v2`, we recommend using a structured approach to define routing methods for easier management of request/response structures and their parameter binding. Please refer to: [Standard Router](../路由管理/路由管理-路由注册/路由注册-规范路由/路由注册-规范路由.md)
:::
Usage example:

Expand Down Expand Up @@ -107,13 +107,13 @@ func main() {
}
```

In this example, we define two structs: `RegisterReq` for parameter reception and `RegisterRes` for data return.
In this example, we defined two structs: `RegisterReq` for binding request parameters and `RegisterRes` for response data.

We use `r.Parse(&req)` to convert the client-submitted parameters to a `RegisterReq` object. When the conversion is successful, the `req` variable will be initialized and assigned (default is `nil`); otherwise, the method returns an `err` and the `req` variable is `nil`. The return data structure is defined using `RegisterRes`, and the return format is `JSON`, implemented via `r.Response.WriteJsonExit`. This method converts `RegisterRes` to `JSON` format based on the `json` tags defined internally and exits the current service method without executing subsequent logic.
We use `r.Parse(&req)` to bind client-submitted parameters to a `RegisterReq` object. When the binding is successful, the `req` variable will be initialized with the bound values (by default it's `nil`), otherwise, this method returns `err` and the `req` variable remains `nil`. The response data structure is defined through `RegisterRes`, and the return format is `JSON`, implemented through `r.Response.WriteJsonExit`. This method converts `RegisterRes` to `JSON` format according to its internal defined `json` tags and exits the current service method.

To demonstrate the test result, the `Data` attribute of the normal return result returns the `RegisterReq` object. Since this object does not have a bound `json` tag, the returned `JSON` field will have its attribute names.
To demonstrate the binding effect, here we return the `RegisterReq` object in the normal return result's `Data` property. Since this object doesn't have `json` tags bound, the returned `JSON` fields will be its property names.

After execution, we test it using the `curl` tool:
Let's test it with the `curl` tool:

```bash
$ curl "http://127.0.0.1:8199/register?name=john&password1=123&password2=456"
Expand All @@ -123,4 +123,4 @@ $ curl -d "name=john&password1=123&password2=456" -X POST "http://127.0.0.1:8199
{"code":0,"error":"","data":{"Name":"john","Pass":"123","Pass2":"456"}}
```

We used both `GET` and `POST` submission methods for testing. You can see that the server perfectly receives the submitted parameters and completes the object conversion.
We used both `GET` and `POST` submission methods for testing, and we can see that the server can perfectly bind the submitted parameters to the struct object.
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ Parameter requests, data validation, `OpenAPIv3`, command management, database O
| Tag (Abbreviation) | Full Name | Description | Documents |
| --- | --- | --- | --- |
| `v` | `valid` | Data validation tag. | [Struct Validation - Example](核心组件/数据校验/数据校验-参数类型/数据校验-Struct校验/Struct校验-基本使用.md) |
| `p` | `param` | Custom request parameter matching. | [Request - Object Conversion](WEB服务开发/请求输入/请求输入-对象处理.md) |
| `p` | `param` | Custom request parameter matching. | [Request - Parameter Binding](WEB服务开发/请求输入/请求输入-对象处理.md) |
| `d` | `default` | Default value binding for request parameters. | [Request - Default Value](WEB服务开发/请求输入/请求输入-默认值绑定.md) |
| `orm` | `orm` | ORM tag, used to specify table name, association relationships. | [Dao/Do/Entity Generating](开发工具/代码生成-gen/数据规范-gen%20dao.md)<br />[Model Association - With](核心组件/数据库ORM/ORM链式操作/ORM链式操作-模型关联/模型关联-静态关联-With特性.md) |
| `dc` | `description` | Generic struct property description, used by both ORM and interfaces. Belongs to the framework's default property description tag. | |
Expand Down

0 comments on commit 663e632

Please sign in to comment.