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. a链接内容过长,换行

    上图为溢出情况,此情况均为 英文或数字,但亲测,中文也可正常换行. 添加   word-wrap: break-word;  后,正常换行. 若不希望换行,设为  white-space: nowra ...

  2. 【内容摘录自 MDN】变量作用域

    有如下自定义函数:(此函数为全局函数,任何地方均可调用) function output(value) { var para = document.createElement('p'); docume ...

  3. centos彻底卸载mysql(不保留数据)

    1. rpm -qa | grep -i mysql 查找已经安装的mysql. MySQL-server-5.6.43-1.el6.x86_64 MySQL-client-5.6.43-1.el6. ...

  4. Codeforces Round #586 (Div. 1 + Div. 2)E(拓扑排序,思维)

    #include<bits/stdc++.h>using namespace std;int n,m,s; vector<int>edge[200007];queue<i ...

  5. 【PAT甲级】1036 Boys vs Girls (25 分)

    题意: 输入一个正整数N(题干没指出范围,默认1e5可以AC),接下来输入N行数据,每行包括一名学生的姓名,性别,学号和分数.输出三行,分别为最高分女性学生的姓名和学号,最低分男性学生的姓名和学号,前 ...

  6. freemarker 作为 word 模板实现下载功能

    1:新建一个.doc 文档写好自己要导出文字如下图 2:把word 文档另存为xml 格式的文件用编辑器打开如图下,(如果你打开文件里面的标签没换行格式,那么你在myeclipse 新建一个jsp 文 ...

  7. [经验] Linux 怎么连接 Xshell?

    (1) 首先, 你要先有一个可以正常运行的 Linux 系统, 当然一般情况下我们是把这个系统放在虚拟机里的, 我所使用的是 ubuntu-18.04.2-live-server-amd64.iso ...

  8. Ubuntu18.04-MySQL8.0-表名大小写敏感-远程连接

    1.卸载 停止服务 sudo service mysql stop 删除mysql服务 sudo apt-get remove mysql-server 删除其他组件 sudo apt-get aut ...

  9. requests---requests封装请求类型

    我们在做自动化的时候,肯定是代码越简洁越好,代码重复量越少越好,这里呢,我们可以通过把requests的请求类型都封装起来,这样编写用例的时候可以直接进行请求 requests方法封装 我们通常用的最 ...

  10. ADV-292 计算行列式 java

    问题描述 //据说很多人的题目会有一大堆废话,本傻×就不在这里废话了. 给定一个N×N的矩阵A,求|A|. 输入格式 第一行一个正整数N. 接下来N行,每行N个整数,第i行第j个数字表示A[i][j] ...