http-template实现原生分页

发布时间 2023-10-27 17:07:03作者: 青烟绕指柔

 

package main

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"html/template"
	"io"
	"math"
	"net/http"
	"os"
	"strconv"
)

// 商品结构体

type Goods struct {
	Id          int
	Name        string
	Price       float64
	Stock       int
	Category    string
	Image       string
	Description string
}

// 添加

func Add(w http.ResponseWriter, r *http.Request) {

	if r.Method == "GET" {
		temp, err := template.ParseFiles("./static/form.html")
		if err != nil {
			panic("模版加载失败")
		}
		m := make(map[string]interface{})
		m["title"] = "商品添加"

		temp.Execute(w, m)

	} else if r.Method == "POST" {
		//接收文件
		file, info, err := r.FormFile("image")
		if err != nil {
			panic("文件获取失败")
		}
		defer file.Close()
		//文件上传
		path := "static/img/" + info.Filename
		f, error := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
		if error != nil {
			panic("文件创建失败")
		}
		io.Copy(f, file)
		//连接数据库
		dsn := "root:root@tcp(127.0.0.1:8889)/2110a"
		db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
		if err != nil {
			panic("数据库连接失败")
		}
		//接收数据
		name := r.FormValue("name")
		price, _ := strconv.ParseFloat(r.FormValue("price"), 64)
		stock, _ := strconv.Atoi(r.FormValue("stock"))
		category := r.FormValue("category")
		description := r.FormValue("description")

		goods := Goods{
			Name:        name,
			Price:       price,
			Stock:       stock,
			Category:    category,
			Image:       path,
			Description: description,
		}

		err = db.Create(&goods).Error
		if err != nil {
			panic("添加失败")
		}
		http.Redirect(w, r, "/list", http.StatusSeeOther)
	}

}

// 分页

func List(w http.ResponseWriter, r *http.Request) {
	//1.总条数
	dsn := "root:root@tcp(127.0.0.1:8889)/2110a"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("数据库连接失败")
	}
	var count int64
	db.Model(Goods{}).Count(&count)
	//2,每页显示条数
	size := 2
	//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 goods []Goods
	db.Limit(size).Offset(offset).Find(&goods)

	var pages []int
	for i := 1; i <= totalPage; i++ {
		pages = append(pages, i)
	}
	//上一页
	prev := page - 1
	if prev < 1 {
		prev = 1
	}
	//下一页
	next := page + 1
	if next > totalPage {
		next = totalPage
	}

	m := make(map[string]interface{})
	m["goods"] = goods
	m["total_page"] = totalPage
	m["prev"] = prev
	m["next"] = next
	m["pages"] = pages

	temp, _ := template.ParseFiles("./static/list.html")
	temp.Execute(w, m)

}

func main() {
	http.HandleFunc("/add", Add)   //添加
	http.HandleFunc("/list", List) //分页

	//设置静态目录
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))

	http.ListenAndServe("localhost:8080", nil)
}