go gin web develop tool library,includes pagination, middleware, pageSearch, response and other functions
$ go get -u github.com/qm012/dun
With Go module support, simply add the following import
import "github.com/qm012/dun"
type SearchUserinfoReq struct {
Query string `json:"query" binding:"required,max=1000"`
dun.PageSearch
}
// for gorm paging
// Part of the code is omitted
func gormPaging(req *SerchUserinfoReq) (*dun.PageInfo, err){
var (
count int64
userinfo Userinfo
)
err := *gorm.DB.Model(&userinfo).Select("id").Where(cmd, values...).Count(&count).Error
if err != nil {
return nil, err
}
userinfoList := make([]*Userinfo, 0, req.PageSize)
err = *gorm.DB.Where(cmd, values...).Order(req.SortByMysql(nil, "id")).Limit(req.PageSize).Offset(req.Offset(count)).Find(&userinfos).Error
if err !=nil {
return nil, err
}
info := dun.NewPageInfo(count, userinfoList).SetPageSize(req.PageNum, req.PageSize)
// info object can be used by the frontend
return info, nil
}
// for mongo paging
// Part of the code is omitted
func mongoPaging(req *SerchUserinfoReq) (*dun.PageInfo, err){
count, err := *mongo.Collection.CountDocuments(context.Background(), bson.D{})
if err != nil {
return nil, err
}
opt := options.Find().
SetLimit(int64(req.PageSize)).
SetSkip(int64(req.Offset(count)))
cursor,err:=*mongo.Collection.Find(ctx, filter, opt)
if err != nil {
return nil, err
}
userinfoList := make([]*Userinfo, 0, req.PageSize) // cursor.All(ctx, &userinfos)
info := dun.NewPageInfo(count, userinfoList).SetPageSize(req.PageNum, req.PageSize)
// info object can be used by the frontend
return info, nil
}
P.S.:The value of offset
depends on whether the current page exceeds the maximum number of pages. By default, the maximum number of pages is the main number. You can also call dun.DisableCalcPageNum()
to cancel the calculation,dun.DisableCalcPageNum()
global valid
func GetUserinfoService(req *SearchUserinfoReq) {
// get request object data
sortFieldMap := map[string]struct{}{
"id": {},
"name":{},
"sort":{},
}
// Prevents sql injection. Properties are valid when they exist in sortFieldMap
`example1:`*gorm.DB.Where(cmd, values...).Order(req.SortByMysql(sortFieldMap))
// req.SortField level gt customField
`example2:`*gorm.DB.Where(cmd, values...).Order(req.SortByMysql(sortFieldMap, "id"))
totalCount := 290 // total records,data source: Select/Find mysql/mongo data
offset:=req.Offset(totalCount)
`example mysql:`*gorm.DB.Where(cmd, values...).Limit(req.PageSize).Offset(offset)
`example mongo:`opt := options.Find().
SetLimit(int64(req.PageSize)).
SetSkip(int64(offset))
}
The dun web tool is open-sourced software licensed under the Apache license.
The following project had particular influence on dun's design.
- pagehelper/Mybatis-PageHelper Mybatis通用分页插件