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. 简单聊一聊Ansible自动化运维

    一.Ansible概述 Ansible是今年来越来越火的一款开源运维自动化工具,通过Ansible可以实现运维自动化,提高运维工程师的工作效率,减少人为失误.Ansible通过本身集成的非常丰富的模块 ...

  2. 「快学springboot」SpringBoot整合freeMark模板引擎

    前言 虽然现在流行前后端分离开发和部署,但是有时候还是需要用到服务端渲染页面的.比如:需要考虑到SEO优化等问题的时候,FreeMark其实还是很有作用的.本人的博客本来是用React开发的,但是后来 ...

  3. VUE学习笔记二

    package.json不可以写注释!!!!!!!!!!初始化:npm init -y 有时候使用 npm i node-sass -D 装不上,这时候,就必须使用  cnpm i node-sass ...

  4. rem与部分手机 字体偏大问题

    原因是部分手机自己设置了巨无霸字体.

  5. 「SDOI2013」森林

    「SDOI2013」森林 传送门 树上主席树 + 启发式合并 锻炼码力,没什么好说的. 细节见代码. 参考代码: #include <algorithm> #include <cst ...

  6. 「NOI2005」维护数列

    「NOI2005」维护数列 传送门 维护过程有点像线段树. 但我们知道线段树的节点并不是实际节点,而平衡树的节点是实际节点. 所以在向上合并信息时要加入根节点信息. 然后节点再删除后编号要回退(栈), ...

  7. 108、Java中String类之字符串文本替换

    01.代码如下: package TIANPAN; /** * 此处为文档注释 * * @author 田攀 微信382477247 */ public class TestDemo { public ...

  8. 使用mybase、Typora搭配坚果云实现个人云笔记

    如果我们没有使用印象笔记.有道云之类的云笔记,那么就会遇到一个问题,比如我在公司是用的公司的电脑,然后下班回家用的自己的电脑,那么我在公司写的文档,比如markdown 文件,mybase知识管理工具 ...

  9. 笔记||Pyhthon3进阶之多线程操作共享数据

    # 多线程操作共享数据--------------------------------------------------------------- # import threading# 使用锁# ...

  10. 吴裕雄--天生自然PYTHON爬虫:使用BeautifulSoup解析中国旅游网页数据

    import requests from bs4 import BeautifulSoup url = "http://www.cntour.cn/" strhtml = requ ...