当前位置:网站首页>Go project practice - parameter binding, type conversion

Go project practice - parameter binding, type conversion

2022-07-05 10:39:00 Golang Chinese community

goshop Update of open source projects > remarks : The code used in the previous project has been shared GitHub In the , And the codes that will appear in all projects in the future will be submitted , Welcome to consult . If you are interested, you can order star Oh ~ https://gitee.com/jobhandsome/goshop/ Recently, I am studying the microservice framework go-zero, No updates , Say sorry here , New functions will be continuously updated later . Please keep an eye on ~~~~ Today, consider parameter binding acquisition . There must be some doubts here , Didn't you encapsulate the method of getting all parameters before ? Looking back, we encapsulated the method of obtaining all parameters , Can only be `POST` request , And the request method must be :`application/x-www-form-urlencoded` Can be obtained normally , It's very limited .* demand 1: Use any request method , Any request format can get the specified value ?* demand 2: Acquired `struct` Type parameter , convert to `map` Type is used for `gorm` Of `DB` Inquire about ?#### By analyzing the above two requirements, we get several conclusions :* `gin` In the framework, you can use parameter binding to obtain the parameters of the request by any request method and request type * `gin` Framework for the integration `gorm`, Use `DB.Where` In conditional query , Need to `map` Array format of type , need `struct turn map`.#### Now that you know what to do , Let's start. : First , First, get the parameters by binding :```go//1. First define the incoming parameters , Use here form Binding ,json For the alias type ParamsRequest struct { Page int64 `form:"page" binding:"required" json:"page"` PageSize int64 `form:"pageSize" binding:"required" json:"pageSize"` Name string `form:"name" json:"name"`}//2. Use binding to get the parameters of the request ctx => *gin.Contextvar params ParamsRequestif err := ctx.ShouldBind(&params); err != nil { utils.Fail(ctx, " Parameter error :"+err.Error(), nil) return}``` After getting the parameters , Let's use parameters `gorm` Of `DB.Where` Inquire about : First of all `struct` transformation `map````go// Corresponding method AnyToMap interface turn mafunc AnyToMap(v any) (map[string]any, error) { dataJson, err := json.Marshal(v) if err != nil { return nil, err } var MapData map[string]any err = json.Unmarshal(dataJson, &MapData) if err != nil { return nil, err } return MapData, nil}``` need Filter `page` and `pageSize`, Those who do not participate in the query ```goParamsFilter := utils.ParamsFilter("page,pageSize", paramsMap)// Filter keyfunc ParamsFilter(isFilterStr string, params map[string]any) map[string]any { var data = make(map[string]any) for key, value := range params { if value != "" { find := strings.Contains(isFilterStr, key) if !find { data[key] = value } } } return data}``` The front is all upholstery , Now is the point , Use `gorm` Data query ```go// obtain gorm Of DB Handle DB := config.GetDB()// It's good to use your own defined model here var Result []*model.Category// Use Scopes Pass in the pointer to page resErr := DB.Scopes(Paginate.Paginate(strconv.FormatInt(params.Page, 10), strconv.FormatInt(params.PageSize, 10))).Where(ParamsFilter).Find(&Result).Error// The return error of the query , If there is an error , Just go back to if resErr != nil { utils.Fail(ctx, resErr.Error(), nil) return}// For queries struct Array transformation Tree structure ToTree var category model.CategoryResultLists := category.ToTree(Result)utils.Success(ctx, " To be successful ", ResultLists)``` Corresponding `model` file :```gotype Category struct { gorm.Model Name string `form:"name" binding:"required" json:"name" gorm:"varchar(255);not null;default:'';comment:' Category name '"` // Category name Pid int64 `form:"pid" json:"pid" gorm:"size:11;not null;default:0;comment:' Classification node '"` // Classification node :0 The root node Icon string `form:"icon" json:"icon" gorm:"varchar(255);not null;default:'';comment:' Category icon '"` // Category icon State int64 `form:"state" json:"state" gorm:"size:1;not null;default:0;comment:' Classification status :0 not enabled ,1 Enabled '"` // Classification status :0 not enabled ,1 Enabled Sort int64 `form:"sort" json:"sort" gorm:"size:11;not null;default:0;comment:' Sorting and sorting '"` // Sorting and sorting Tag string `form:"tag" json:"tag" gorm:"varchar(255);not null;default:0;comment:' Category labels '"` // Category labels Children *CategoryTrees `json:"children"`}// CategoryTrees Binary tree list type CategoryTrees []*Category// ToTree Convert to tree structure func (Category) ToTree(data CategoryTrees) CategoryTrees { // Definition HashMap The variable of , And initialization TreeData := make(map[int64]*Category) // Reorganize the data first : With data ID As an outer layer key Number , In order to combine the data of subtree for _, item := range data { TreeData[int64(item.ID)] = item } // Definition RoleTrees Structure var TreeDataList CategoryTrees // Start generating tree for _, item := range TreeData { // If there is no root node tree , Is the root node if item.Pid == 0 { // Append to TreeDataList In the structure TreeDataList = append(TreeDataList, item) // Skip the loop continue } // adopt above TreeData HashMap The combination of , Determine whether there is a root node // If there is a root node , Then the node should be processed if pItem, ok := TreeData[item.Pid]; ok { // Judge whether there are child nodes in the current cycle , If not, they are combined as child nodes if pItem.Children == nil { // Write child nodes children := CategoryTrees{item} // Insert into When the child node field of the secondary structure , In the form of a pointer pItem.Children = &children // Skip the current loop continue } // Append to the structure in the form of pointer address *pItem.Children = append(*pItem.Children, item) } } return TreeDataList}``` Here we are , We have achieved the functions required above . For more features, please continue to pay attention to !!!!!#### Planet address :https://t.zsxq.com/03MJM7YfI#### ** Official account 「 Programmer Joe 」**![ Programmer Joe ](https://www.qsjob.fun/zb_users/upload/2022/07/202207041451541741109.jpg " Programmer Joe ")
原网站

版权声明
本文为[Golang Chinese community]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051011239140.html