Go语言 Note
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的更多相关文章
- KOTLIN开发语言文档(官方文档) -- 2.基本概念
网页链接:https://kotlinlang.org/docs/reference/basic-types.html 2. 基本概念 2.1. 基本类型 从可以在任何变量处理调用成员函数和属性 ...
- go语言结构体
定义: 是一种聚合的数据类型,是由零个或多个任意类型的值聚合成的实体. 成员: 每个值称为结构体的成员. 示例: 用结构体的经典案例处理公司的员工信息,每个员工信息包含一个唯一的员工编号.员工的名字. ...
- C语言栈调用机制初探
学习linux离不开c语言,也离不开汇编,二者之间的相互调用在源代码中几乎随处可见.所以必须清楚地理解c语言背后的汇编结果才能更好地读懂linux中相关的代码.否则会有很多疑惑,比如在head.s中会 ...
- C语言查缺补漏
7.用ucontext实现简单的用户空间协作多线程 转 http://blog.chinaunix.net/uid-26000137-id-3973004.html http://blog.csdn. ...
- 【原】iOS学习之苹果原生代码实现Autolayout和VFL语言
1.添加约束的规则 在创建约束之后,需要将其添加到作用的view上 在添加时要注意目标view需要遵循以下规则: 1)对于 两个同层级view之间 的约束关系,添加到它们的父view上 2)对于 两个 ...
- Rust语言的多线程编程
我写这篇短文的时候,正值Rust1.0发布不久,严格来说这是一门兼具C语言的执行效率和Java的开发效率的强大语言,它的所有权机制竟然让你无法写出线程不安全的代码,它是一门可以用来写操作系统的系统级语 ...
- [译]MVC网站教程(一):多语言网站框架
本文简介 本博文介绍了 Visual Studio 工具生成的 ASP.NET MVC3 站点的基本框架:怎样实现网站的语言的国际化与本地化功能,从零开始实现用户身份认证机制,从零开始实现用户注册机制 ...
- 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 ...
- C语言 第七章 数组与字符串
一.数组 1.1.数组的概念 用来存储一组相同类型数据的数据结构.有点像班上放手机的手机袋,超市的储物柜. 特点:只能存放一种类型的数据,如全部是int型或者全部是char型,数组里的数据成为元素. ...
随机推荐
- idea提交项目到码云
1.安装Git 2.在码云上创建项目 3.在IDEA提交项目到码云
- php 基础 语句include和require的区别是什么?为避免多次包含同一文件,可用(?)语句代替它们?
require->require是无条件包含也就是如果一个流程里加入require,无论条件成立与否都会先执行 require include->include有返回值,而require没 ...
- js面试必考:this
this是前端面试中必考的基础知识点,也是新手小白在做项目中经常晕头转向的问题.但其实this不难理解. 判断this指向时,记住以下几点: 判断函数类型, 1.1 如果是箭头函数,则为第一个包裹箭头 ...
- @implementer,抽象类,接口
@implementer,抽象类,接口 1. implementer 在看twisted源码时,经常出现@implementer(IReactorFDSet) 它来自zope.interfa ...
- Unity初步 基本拼图实现
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; ...
- Ubuntu12.04LTS中安装和使用Spin
https://blog.csdn.net/jackandsnow/article/details/94434481 把第三步 安装tk(在wish中):apt-get install wish 改为 ...
- (未解决)flume监控目录,抓取文件内容推送给kafka,报错
flume监控目录,抓取文件内容推送给kafka,报错: /export/datas/destFile/220104_YT1013_8c5f13f33c299316c6720cc51f94f7a0_2 ...
- JS事件委托或者事件代理原理以及实现
事件委托(事件代理)原理:简单的说就是将事件交由别人来执行,就是将子元素的事件通过冒泡的形式交由父元素来执行. 为什么要用时间委托? 在JavaScript中,添加到页面上的事件处理程序数量将直接关系 ...
- webpack配置文件里loader的执行顺序:从下到上,从右到左; css-loader开启css模块化modules: true,
注释: options:{ importLoaders: 2 } 解决样式文件里使用@import 'xxx.xxx' 的问题 module: { rules: [{ test: /\.scss$/, ...
- 4.使用Redis+Flask维护动态代理池
1.为什么使用代理池 许多⽹网站有专⻔门的反爬⾍虫措施,可能遇到封IP等问题. 互联⽹网上公开了了⼤大量量免费代理理,利利⽤用好资源. 通过定时的检测维护同样可以得到多个可⽤用代理理. 2.代理池的要 ...