1.简单的CURD之搭建基础框架

//路由层
func Router(rg *gin.RouterGroup){
rg.GET("/getsupplier", facility.GetSupplierList)//查询
rg.POST("/addsupplier", facility.AddSupplier)//添加
rg.POST("/editsupplier", facility.EditSupplier)//编辑
rg.GET("/deletesupplier", facility.DeleteSupplier)//删除
}
//api层
//查询
fun GetSupplierList(ctx *gin.Context){
  result := dal.GetSupplierList()
  ctx.JSON(http.StatusOK, &gin.H){
    "data": result,
  }
} //添加
func AddSupplier(ctx *gin.Context){
  var supplier model.FacilitySupplier
if err := ctx.ShouldBindJSON(&supplier); err != nil{
return
}
staff := fModel.GetStaff(ctx)
staff := staff.StaffName
code, result := dal.Addsupplier(&supplier, staffName)
  ctx.JSON(http.StatusOK, &gin.H){
"code": code,
    "data": result,
  }
} //编辑
func EditSupplier(ctx *gin.Context){
  var supplier model.FacilitySupplier
if err := ctx.ShouldBindJSON(&supplier); err != nil{
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
staff := fModel.GetStaff(ctx)
staff := staff.StaffName
code, result := dal.Editsupplier(&supplier, staffName)
  ctx.JSON(http.StatusOK, &gin.H){
"code": code,
    "data": result,
  }
} //删除
fun GetSupplierList(ctx *gin.Context){
  id, _ := strconv.Atoi(ctx.Query("id"))
code, message := dal.DeleteSupplier(id)
  ctx.JSON(http.StatusOK, &gin.H){
    "code": code,
"message": message,
  }
}
//dal层
//查询
func GetSupplierList()([]model.FacilitySupplier){
var results []model.FacilitySupplier
tx := fiorm.BeginTransaction()
defer tx.EndTransaction()
selSQL := `select * from table`
selQ := tx.NewQuery()
selQ.Raw(selSQL).Scan(&results)
return results
} //添加
func AddSupplier(parm * model.FacilitySupplier ,staffName string)(int ,string){
var code int
var message string
tx := fiorm.BeginTransaction()
defer tx.EndTransaction()
facilitySupplier := model.FacilitySupplier{
Name:param.Name,
CreateTime:currentTime,
}
insertQ := tx.NewQuery()
insertQ.InsertItem(&facilitySupplier)
if tx.Error != nil{
code =
message = "写入失败"
return code, message
}
code =
message = "写入成功"
return code, message
} //编辑
func EditSupplier(parm * model.FacilitySupplier ,staffName string)(int ,string){
var code int
var message string
currentTime:=time.Now()
conn := fiorm.NewQuery()
ID := param.ID
Name := name
CreateTime := currentTime
sql := `update facility_supplier set id = ? ,name = ? , create_time = ?`
if tx.Error != nil{
code =
message = "编辑失败"
return code, message
}
code =
message = "编辑成功"
return code, message
} //删除
func DeleteSupplier(id int)(int ,string){
var code int
var message string
delSQL := `delete from facility_supplier where id = ?`
conn := fiorm.NewQuery()
conn.Exec(delSAQL, id)
if tx.Error != nil{
code =
message = "删除失败"
return code, message
}
code =
message = "删除成功"
return code, message
}
//model层
//数据库的字段
type FacilitySupplier struct{
ID int `gorm:"primary_key,column:id" json:"id"`
Name null.String `gorm:"column:name" json:"name"`
CreateTime time.Time `gorm:"column:create_time" json:"create_time"`
} func (f * FacilitySupplier) TableName() string{
return "table"
}

2.递归遍历(结构树)

//api层
fun Test(ctx *gin.Context){
  code, result := dal.Test()
  ctx.JSON(http.StatusOK, &gin.H){
"code": code,
    "data": result,
  }
}
//dal层
func Test () (int,[]model.Category) {
var code int
var facilitycategory []model.FacilityCategory
var results []model.Category
tx := fiorm.BeginTransaction()
defer tx.EndTransaction()
selSQL :=`SELECT * FROM facility_category`
selQ := tx.NewQuery()
selQ.Raw(selSQL).Scan(&facilitycategory)
if tx.Error != nil {
code =
return code, results
}else {
var category model.Category
for i := ; i < len(facilitycategory);i++{
if facilitycategory[i].ParentFacilityCategoryID == {
var list = test1(facilitycategory, facilitycategory[i].ID)
category.ID = facilitycategory[i].ID
category.FacilityCategoryName = facilitycategory[i].FacilityCategoryName
category.Childern = list
results = append(results,category)
}
}
code =
return code, results
}
} func test1 (arr []model.FacilityCategory,id int)(arrt []model.Category) {
var category model.Category
for i :=;i<len(arr); i++{
if arr[i].ParentFacilityCategoryID == id{
var res = test1(arr, arr[i].ID)
category.ID = arr[i].ID
category.FacilityCategoryName = arr[i].FacilityCategoryName
category.Childern =res
arrt = append(arrt,category)
}
}
return
}
//model层
type Category struct {
ID int `json:"facility_category_id"`
FacilityCategoryName string `json:"facility_category_name"`
Childern []Category
}

3.搜索和分页

//api层
//查询
fun GetSupplierList(ctx *gin.Context){
PageSize,_ := strconv.Atoi(ctx.Query("pagesize"))
PageIndex,_ := strconv.Atoi(ctx.Query("pageindex"))
Name := ctx.Query("name")
Type := strconv.Atoi(ctx.Query("type"))
Param := model.FacilitySupplierParam{
PageSize: PageSize,
PageIndex: PageIndex,
Name: Name,
Type: Type,
}
  code, result := dal.GetSupplierList(&Param)
  ctx.JSON(http.StatusOK, &gin.H){
"code": code,
    "data": result,
  }
}
//dal层
func GetSupplierList(param *model.FacilitySupplierParam)(int, model.SupplierListModel){
var code int
pageSize := param.PageSize
pageIndex := param.PageIndex
Name := param.Name
Type := param.Type
var facilitySupplier []model.FacilitySupplier
var results model.SupplierListModel
var count model.Count
tx := fiorm.BeginTransaction()
defer tx.EndTransaction()
selSQL := `select * from facility_supplier where = `
if Name != ""{
selSQL += "and name = ' " + Name +" ' "
}
if Type > {
selSQL += "and type = ' " + strconv.Itoa(Type) +" ' "
}
selSQL += `LIMIT ?,? `
selQ := tx.NewQuery()
selQ.Raw(selSQL,(pageIndex-)*pageSize, pageSize).Scan(&facilitySupplier)
countSQL := `select count() as count from facility_supplier where =`
if Name != ""{
countSQL += "and name = ' " + Name +" ' "
}
if Type > {
countSQL += "and type = ' " + strconv.Itoa(Type) +" ' "
}
countQ := tx.NewQuery()
countQ.Raw(countSQL).Scan(&count)
if tx.Error != nil{
code =
return code, results
}
results.ICurPage = pageIndex
results.IPageSize = pageSize
results.TotalItems = count.Count
if count.Count != {
if(count.Count % pageSize) == {
results.TotalPages = count.Count / pageSize
}else{
results.TotalPages = count.Count / pageSize +
}
}else{
results.TotalPages =
}
results.Items = facilitySupplier
code =
return code, results
}
//model层
//查询的条件
type FacilitySupplierParam struct{
PageSize int `json:"pagesize"`
PageIndex int `json:"pageindex"`
Name int `json:"name"`
Type int `json:"type"`
} //分页查询
type SupplierListModel struct{
ICurPage int //当前页索引
IPageSize int //每页的记录数
TotalPages int //总页数
TotalItems int //总记录数
Items []FacilitySupplier
} //字段
type FacilitySupplier struct{
CreateTime time.Time `create_time`
CreateUser string `create_user`
ID int `facility_supplier_id`
Name null.string `name`
Type null.Int `type`
Company null.string `company`
} //总数
type Count struct{
Count int
}

4.EXECL导出

//api层
func ServeExcel(c *gin.Context) { file := xlsx.NewFile()
sheet, err := file.AddSheet(fmt.Sprintf("Sheet1"))
if err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
return
}
columns := []string {"city_id","city_name","latitude","longtitude"}
//添加表头
newHeader := sheet.AddRow()
for _, col := range columns {
newHeader.AddCell().SetValue(col)
}
rows := dal.Test()
//添加内容
for i := ; i < len(rows); i++ {
newRow := sheet.AddRow()
cell := []string {rows[i].CityID,rows[i].CityName , rows[i].Latitude.String ,rows[i].Longtitude.String}
for _, cells := range cell {
newRow.AddCell().SetValue(cells)
}
}
var b bytes.Buffer
if err := file.Write(&b); err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
return
}
downloadName := time.Now().UTC().Format("data-20060102150405.xlsx")
c.Header("Content-Description", "File Transfer")
c.Header("Content-Disposition", "attachment; filename="+downloadName)
c.Data(http.StatusOK, "application/octet-stream", b.Bytes())
}
//dal层
func Test()([]model.City){ tx := fiorm.BeginTransaction()
defer tx.EndTransaction()
var city []model.City
ctSQL := `SELECT * FROM city `
ctQ := tx.NewQuery()
ctQ.Raw(ctSQL).Scan(&city)
return city
}
//model层

type City struct{
CityID string `gorm:"primary_key;column:city_id" json:"city_id"`
CityName string `gorm:"column:city_name" json:"city_name"`
Latitude null.string `gorm:"column:latitude" json:"latitude"`
Longtitude null.string `gorm:"column:longtitude" json:"longtitude"`
}

Go语言 Note的更多相关文章

  1. KOTLIN开发语言文档(官方文档) -- 2.基本概念

    网页链接:https://kotlinlang.org/docs/reference/basic-types.html 2.   基本概念 2.1.  基本类型 从可以在任何变量处理调用成员函数和属性 ...

  2. go语言结构体

    定义: 是一种聚合的数据类型,是由零个或多个任意类型的值聚合成的实体. 成员: 每个值称为结构体的成员. 示例: 用结构体的经典案例处理公司的员工信息,每个员工信息包含一个唯一的员工编号.员工的名字. ...

  3. C语言栈调用机制初探

    学习linux离不开c语言,也离不开汇编,二者之间的相互调用在源代码中几乎随处可见.所以必须清楚地理解c语言背后的汇编结果才能更好地读懂linux中相关的代码.否则会有很多疑惑,比如在head.s中会 ...

  4. C语言查缺补漏

    7.用ucontext实现简单的用户空间协作多线程 转 http://blog.chinaunix.net/uid-26000137-id-3973004.html http://blog.csdn. ...

  5. 【原】iOS学习之苹果原生代码实现Autolayout和VFL语言

    1.添加约束的规则 在创建约束之后,需要将其添加到作用的view上 在添加时要注意目标view需要遵循以下规则: 1)对于 两个同层级view之间 的约束关系,添加到它们的父view上 2)对于 两个 ...

  6. Rust语言的多线程编程

    我写这篇短文的时候,正值Rust1.0发布不久,严格来说这是一门兼具C语言的执行效率和Java的开发效率的强大语言,它的所有权机制竟然让你无法写出线程不安全的代码,它是一门可以用来写操作系统的系统级语 ...

  7. [译]MVC网站教程(一):多语言网站框架

    本文简介 本博文介绍了 Visual Studio 工具生成的 ASP.NET MVC3 站点的基本框架:怎样实现网站的语言的国际化与本地化功能,从零开始实现用户身份认证机制,从零开始实现用户注册机制 ...

  8. LeetCode Note 1st,practice makes perfect

    1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to a ...

  9. C语言 第七章 数组与字符串

    一.数组 1.1.数组的概念 用来存储一组相同类型数据的数据结构.有点像班上放手机的手机袋,超市的储物柜. 特点:只能存放一种类型的数据,如全部是int型或者全部是char型,数组里的数据成为元素. ...

随机推荐

  1. Sqoop 一点通

    sqoop 是什么? sqoop 主要用于异构数据: 1. 将数据从hadoop,hive 导入.导出到关系型数据库mysql 等; 2. 将关系型数据库 mysql 中数据导入.导出到 hadoop ...

  2. Python回收机制

    1.小整数对象池 整数在程序中的使用非常广泛,python 为了优化速度,使用了小整数对象池,避免整数频繁申请和销毁和内存空间. Python 对小整数的定义事[-5, 257]这些整数对象的hi提前 ...

  3. JS获取CHECKBOX的值 AND 两个CHECKBOX 循环选中

    获取多选按钮的值 var chk_value = ''; $('input[data-action="checkRole"]:checked').each(function(){ ...

  4. linux搭建jenkins+github详细步骤

    事情缘由: 现在在做的主要工作是通过jenkins+postman实现api的自动化测试,想要达到的效果是,api自动化测试定时跑脚本的同时,github有新的代码提交,jenkins会自动检测部署新 ...

  5. CentOS7虚拟机优化

    CentOS7: 将网卡配置重点关注的地方为: [root@master ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens33 BOOTPROTO=st ...

  6. Java源码-集合-ArrayList

    基于JDK1.8.0_191 介绍   在Java中,对于数据的保存和使用有多种方式,主要的目的是以更少的资源消耗解决更多的问题,数组就是其中的一种,它的特点是所有的数据都保存在内存的一段连续空间中, ...

  7. 第4课.编写通用的Makefile

    1.框架 1. 顶层目录的Makefile 2. 顶层目录的Makefile.build 3. 各级子目录的Makefile 2.概述 1.各级子目录的Makefile: 它最简单,形式如下: obj ...

  8. Openstack----学习笔记

    ceph 分布式存储,用于存放新创建的云主机磁盘镜像文件和磁盘 创建云主机流程记录 简易版本: 上图中所有发送的请求都会存放在rabbit_mq(消息队列)中,各个组件会定时取消息队列中与自己相关的请 ...

  9. vscode调试开发C/C++程序

    https://www.cnblogs.com/TAMING/p/8560253.html

  10. sqlalchemy 连接mysql8.0报 RuntimeError: cryptograpy si requeired for sha256_password 错误

    cryptography is required for sha256_password or caching_sha2_password 需要cryptography模块的支持才能连接需要sha25 ...