原生分页接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | package main import ( "encoding/json" "gorm.io/driver/mysql" "gorm.io/gorm" "math" "net/http" "strconv" ) // 封装接口返回的三要素:1状态 2提示 3数据 type ApiResponse struct { Code int `json: "code" ` Message string `json: "message" ` Data interface {} `json: "data" ` } // 结构体 type House struct { Id int `json: "id" ` Name string `json: "name" ` Price float64 `json: "price" ` Address string `json: "address" ` Cate string `json: "cate" ` Img string `json: "img" ` } // 分页结构体 type PageData struct { House []House `json: "house" ` Count int `json: "count" ` TotalPage int `json: "total_page" ` Prev int `json: "prev" ` Next int `json: "next" ` } // 自定义表名 func (House) TableName() string { return "house" } // 分页接口 func Page(w http.ResponseWriter, r *http.Request) { //连接数据库 dsn := "root:root@tcp(127.0.0.1:8889)/2110a" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { result := ApiResponse{500, "数据库连接失败" , "" } json.NewEncoder(w).Encode(result) } //1.总数 var count int64 db.Model(House{}).Count(&count) //2.每页显示条数 size, _ := strconv.Atoi(r.URL.Query().Get( "size" )) if size == 0 { size = 5 } //3.总页数 totalPage := int(math.Ceil(float64(count) / float64(size))) //4.当前页 page, _ := strconv.Atoi(r.URL.Query().Get( "p" )) if page == 0 { page = 1 } //5.偏移量 offset := (page - 1) * size // 分页查询 var house []House db.Model(House{}).Limit(size).Offset(offset).Find(&house) //上一页 prev := page - 1 if prev < 1 { prev = 1 } //下一页 next := page + 1 if next > totalPage { next = totalPage } pageData := PageData{ House: house, Count: int(count), TotalPage: totalPage, Prev: prev, Next: next, } // 返回接口数据 result := ApiResponse{ Code: 200, Message: "success" , Data: pageData, } json.NewEncoder(w).Encode(result) } func main() { http.HandleFunc( "/api/page" , Page) http.ListenAndServe( "localhost:8080" , nil) } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现