Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize restful pagination with gorm+gin

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to achieve restful pagination in gorm+gin". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "how to achieve restful paging by gorm+gin"!

API's handling of paging seems simple, but it actually hides a crisis. The most common form of paging is something like this

Page count representation: / user/?page=1&size=15&name= Lee

Offset representation: / user/?offset=100&limit=15&name= Lee

The use of page number representation is friendly to front-end development, but is essentially similar to offset representation. Here we will use jinzhu/gorm and gin-gonic/gin to develop a simple paging interface

Paging query URL: http://dev.mojotv.cn:3333/api/ssh-log?client_ip=&page=1&size=10&user_id=0&machine_id=0 returns json result

{"data": [{"id": 28, "created_at": "2019-09-12T14:25:54+08:00", "updated_at": "2019-09-12T14:25:54+08:00", "user_id": 26, "machine_id": 1, "ssh_user": "mojotv.cn" Client_ip: "10.18.60.16", "started_at": "2019-09-12T14:24:05+08:00", "status": 0, "remark": ""}], "ok": true, "page": 1, "size": 10, "total": 1} 1. Define paging struct

/ / PaginationQ gin handler query binding structtype PaginationQ struct {Ok bool `json: "ok" `Size uint `form: "size" json: "size" `Page uint `form: "page" json: "page" `Data interface {} `json: "data" comment: "muster be a pointer of slice gorm.Model"` / / save pagination list Total uint `json: "total" `}

Ok represents no error in business query.

The number of Size displayed per page. Use form tag to accept the url-query parameter of gin

Page current page number, use form tag to accept the url-query parameter of gin

Data content of Data paging

The total number of pages in Total

two。 Data sheet Model

Here, take ssh_log (ssh command log as an example), use GORM to create a MYSQL data table model, and use form tag to accept the url-query parameter of gin as a search condition

Type SshLog struct {BaseModel UserId uint `gorm: "index" json: "user_id" form: "user_id" `/ form tag bind gin url-query parameter MachineId uint `gorm: "index" json: "machine_id" form: "machine_id"` / / form tag bind gin url-query parameter SshUser string `json: "ssh_user" comment: "ssh account" `ClientIp string `json: "client_ip" form: "client_ip" `/ / form tag bind Set the gin url-query parameter StartedAt time.Time `json: "started_at" form: "started_at" `Status uint `json: "status" comment: "0-not marked 2-normal 4-warning 8-dangerous 16-fatal" `Remark string `json: "remark" `Log string `gorm: "type:text" json: "log" `Machine Machine `gorm: "association_autoupdate:false Association_autocreate:false "json:" machine "`User User `gorm:" association_autoupdate:false;association_autocreate:false "json:" user "`}

3. Define the structure of a paged query search

Ssh3ws/internal/h_ssh_log.gotype SshLogQ struct {SshLog PaginationQ FromTime string `form: "from_time" `/ / search start time ToTime string `form: "to_time"` / / search end}

This structure is provided to gin handler as a parameter binding. The methods used are as follows:

Func SshLogAll (c * gin.Context) {query: = & model.SshLogQ {} err: = c.ShouldBindQuery (query) / / start binding url-query parameters to structure if handleError (c, err) {return} list, total, err: = query.Search () / / start mysql business search query if handleError (c, err) {return} / / return data start paging json jsonPagination (c, list, total, & query.PaginationQ)} 4. Paging and search data query

1. Create db-query

two。 Search for non-empty service fields

3. Use the crudAll method to get data

Model/m_ssh_log.gotype SshLogQ struct {SshLog PaginationQ FromTime string `form: "from_time" `ToTime string `form: "to_time" `} func (m SshLogQ) Search () (list * [] SshLog, total uint Err error) {list = & [] SshLog {} / / create db-query tx: = db.Model (m.SshLog) .preload ("User"). Preload ("Machine") / / search for the non-empty service field if m.ClientIp! = "{tx = tx.Where (" client_ip like? ") "%" + m.ClientIp + "%")} / / search time period if m.FromTime! = "& & m.ToTime! =" {tx = tx.Where ("`created_ at` BETWEEN?" AND? ", m.FromTime, m.ToTime)} / / use the crudAll method to obtain data total, err = crudAll (& m.PaginationQ, tx, list) return}

CrudAll method to build sql paging data

Set default parameters

Get total number of searches

Get the offset data

Assemble json paging data

Model/helper.go

Func crudAll (p * PaginationQ, queryTx * gorm.DB, list interface {}) (uint, error) {/ / 1. The default parameter if p.Size < 1 {p.Size = 10} if p.Page < 1 {p.Page = 1} / / 2. The number of searches var total uint err: = queryTx.Count (& total). Error if err! = nil {return 0, err} offset: = p.Size * (p.Page-1) / / 3. Offset data err = queryTx.Limit (p.Size) .offset (offset) .find (list). Error if err! = nil {return 0, err} return total, err} / / 4.json paged data func jsonPagination (c * gin.Context, list interface {}, total uint, query * model.PaginationQ) {c.AbortWithStatusJSON (200,200, gin.H {"ok": true, "data": list "total": total, page: query.Page, "size": query.Size})}

API's handling of paging seems simple, but it actually hides a crisis. The most common form of paging is something like this

Page count representation: / user/?page=1&size=15&name= Lee

Offset representation: / user/?offset=100&limit=15&name= Lee

The use of page number representation is friendly to front-end development, but is essentially similar to offset representation. Here we will use jinzhu/gorm and gin-gonic/gin to develop a simple paging interface

Paging query URL: http://dev.mojotv.cn:3333/api/ssh-log?client_ip=&page=1&size=10&user_id=0&machine_id=0 returns json result

{"data": [{"id": 28, "created_at": "2019-09-12T14:25:54+08:00", "updated_at": "2019-09-12T14:25:54+08:00", "user_id": 26, "machine_id": 1, "ssh_user": "mojotv.cn" "client_ip": "10.18.60.16", "started_at": "2019-09-12T14:24:05+08:00", "status": 0, "remark": ""}], "ok": true, "page": 1, "size": 10, "total": 1} so far. I believe that you have a deeper understanding of "gorm+gin how to achieve restful pagination", you might as well come to the actual operation! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report