原生分页接口

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)
}

  

posted @ 2023-10-28 10:03  青烟绕指柔  阅读(4)  评论(0编辑  收藏  举报