首页 > 其他分享 >http-template实现原生分页

http-template实现原生分页

时间:2023-10-27 17:14:29浏览次数:31  
标签:原生 http err nil static template gorm string

 

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

  

标签:原生,http,err,nil,static,template,gorm,string
From: https://www.cnblogs.com/superzwb/p/17792777.html

相关文章

  • Kubernetes 中使用consul-template渲染配置
    Kubernetes中使用consul-template渲染配置当前公司使用consul来实现服务发现,如Prometheue配置中的target和alertmanager注册都采用了consul服务发现的方式,以此来灵活应对服务的变更。但对于其他服务,是否也有一个通用的方式来使用consul管理配置文件?本文中描述如何使用consul-tem......
  • PCB封装命名规则,本文转载https://www.xjx100.cn/news/432127.html?action=onClick
    SO、SOP、SOIC、MSOP、TSSOP、TSOP、VSSOP、SSOP、SOJ封装详解 1. 简要信息如下: 2.SOP和SOIC的规格多是类似的,现在大多数厂商基本都采用的是SOIC的描述:SOIC8有窄体150mil的(外形封装宽度,不含管脚,下同),管脚间距是1.27mm,如下:有宽体的208mil的,管脚间距是1.27mm,如下:......
  • C#winform软件实现一次编译,跨平台windows和linux兼容运行,兼容Visual Studio原生界面Fo
    一、背景:微软的.netcore开发工具,目前来看,winform界面软件还没有打算要支持linux系统下运行的意思,要想让c#桌面软件在linux系统上运行,开发起来还比较麻烦。微软只让c#的控制台软件支持在linux运行。二、解决方案:我想到的一个方案是自定义封装软件的System.Windows.Forms组件,把......
  • 通过requests库使用HTTP编写的爬虫程序
    使用Python的requests库可以方便地编写HTTP爬虫程序。以下是一个使用requests库的示例:importrequests#发送HTTPGET请求response=requests.get("http://example.com")#检查响应状态码ifresponse.status_code==200:#获取响应内容html=response.text......
  • https://www.modb.pro/db/1717179181560324096 --转载 Oracle 批量更新(BULK)优化技巧
    面对一个需要更新大量数据的任务,我平时的处理方法是通过循环,每N行提交来完成这个任务。这样做的两个主要原因:1、频繁地提交大量小事务比处理和提交一个大事务更快,也更高效2、没有足够的UNDO空间今天在学到了一种新的解决思路,在此记录一下方便后面使用。  假设我们有一个表T,......
  • 2023-10-26 无法访问此网站网址为 http://xxx.yy.com/ 的网页可能暂时无法连接,或者它
    新购一域名,并添加了解析,保存后若干分钟访问该域名,报错显示:原因,我给域名添加的解析地址不正确,所以导致无法找到该服务器,故而报错。看到圈中的【记录值】了吗,这里应该填你的服务器公网ip,如果填错了就无法访问。解决方案,前往你的服务器管理后台,找到域名解析的地方,重新修改解析地......
  • httprunner2.5.7+python3安装报错解决
    1.执行hrun-V报错:ImportError:cannotimportname'Iterable'from'collections'将fromcollectionsimportIterable修改成fromcollections.abcimportIterable 2.执行hrun-V报错:ImportError:cannotimportname'soft_unicode'from'......
  • chrome新版本http自动跳转https问题解决
    虽然是个好功能,但是部分内网业务还没做好https兼容,有的时候手工访问,还是变成https 解决办法:chrome://flags/找到:HTTPSUpgrades,修改disabled,重启解决,当然这个需要需要用户去调整,真正还需要服务去兼容https  ......
  • 使用fluent api调用https接口时忽略证书异常
    不知道为啥,中文互联网对脱胎于httpclient的fluentapi介绍太少了,遇到问题也不知道怎么查,只能自己研究,于是遇到问题赶紧记下来一般情况下我们使用fluent的get方法调用http接口的方式是这样的Request.get(url).connectTimeout(Timeout.ofMilliseconds(5000)).e......
  • LR录制https协议脚本前配置
    LR录制https安全协议脚本前的设置在IE中添加安全证书打开IE浏览器,选择“工具—Internet选项—内容”,点击“证书”导入相应的证书,如下图在LR中配置证书获取pem格式证书因为loadrunner只支持pem格式的证书,所以要将证书转换格式;这里就需要用到openssl工具,进入cmd命令窗口,进入openssl的......