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. java判断文件或文件夹是否在

    public static void main(String[] args) { File file = new File("G:\\Jeff.txt"); File dir = ...

  2. oracle的concat、convert、listagg函数(字符串拼接和类型转换)

    ORACLE几种常用的方法(2) 1.concat常见的用法 : 格式:concat(String1,String2) 说明:concat函数用于将两个字符串连接起来,形成一个单一的字符串 实例: s ...

  3. javascript入门教程02

    JavaScript中的运算符 (1)算术运算符 + :相加 var a=123,b=45; document.write(a+b); - :相减 document.write(a-b); *:相乘 ...

  4. 「题解」「美团 CodeM 资格赛」跳格子

    目录 「题解」「美团 CodeM 资格赛」跳格子 题目描述 考场思路 思路分析及正解代码 「题解」「美团 CodeM 资格赛」跳格子 今天真的考自闭了... \(T1\) 花了 \(2h\) 都没有搞 ...

  5. 八 Spring的IOC的XML和注解的区别及其整合开发

    xml和注解的区别 xml和注解整合开发 注解:取消扫描配置开启注解配置 扫描:<context:component-scan base-package="" />  ...

  6. 【转】python中的闭包详细解析

    一.什么是闭包? 如果一个内嵌函数访问外部嵌套函数作用域的变量,并返回这个函数,则这个函数就是闭包 闭包必须满足三个条件: 1. 必须有一个内嵌函数    2. 内嵌函数必须引用外部嵌套函数中的变量  ...

  7. FiBiNET-学习

    Our main contributions are listed as follows: • Inspired by the success of SENET in the computer vis ...

  8. virtual column make sqlserver using function index

    In sqlserver, it is impossible that if we want to create an function index. Doesn`t means we can not ...

  9. [转]简单总结一下解决 添加 inline-block 后多出来的空隙

    添加 inline-block 后: 查询.借鉴的原网址:http://www.zhangxinxu.com/wordpress/?p=2357 html 结构: <ul class=" ...

  10. Py西游攻关之基础数据类型(五)-集合

    Py西游攻关之基础数据类型 - Yuan先生 https://www.cnblogs.com/yuanchenqi/articles/5782764.html 八 集合(set) 集合是一个无序的,不 ...