gin CRUD
gin CRUD
// units
package dal
//cxg 2022-7-29
import (
"net/url"
"svrGIN/db"
"svrGIN/model"
"github.com/gin-gonic/gin/binding"
"strings"
"svrGIN/log"
"github.com/gin-gonic/gin"
)
func SelectUnits(ctx *gin.Context) {
var arr model.TunitArray
var r model.Res
d := db.GetPG()
where := ctx.Param("where")
where, _ = url.QueryUnescape(where)
where = strings.Trim(where, "/")
if where != "" {
where = " where " + where
}
rows, err := d.Query("select * from tunit" + where)
if err != nil {
r.Status = 500
r.Message = "fail"
r.Exception = err.Error()
ctx.JSON(500, &r)
log.Log("SelectUnits()", err)
return
}
defer d.Close()
for rows.Next() {
var row model.Tunit
rows.Scan(&row.Unitid, &row.Unitname)
arr.Tunits = append(arr.Tunits, &row)
}
arr.Status = 200
arr.Message = "success"
ctx.JSON(200, &arr)
}
func InsertUnits(ctx *gin.Context) {
var arr model.TunitArray
var r model.Res
ctx.ShouldBindBodyWith(&arr, binding.JSON)
d := db.GetPG()
tx, _ := d.Begin()
for _, row := range arr.Tunits {
s := "insert into tunit(unitid,unitname) values ('"
s += row.Unitid + "','" + row.Unitname + "')"
_, err := tx.Exec(s)
if err != nil {
tx.Rollback()
r.Status = 500
r.Message = "fail"
r.Exception = err.Error()
ctx.JSON(500, &r)
log.Log("InsertUnits()", err)
return
}
}
tx.Commit()
r.Status = 200
r.Message = "success"
ctx.JSON(200, &r)
}
func UpdateUnits(ctx *gin.Context) {
var arr model.TunitArray
var r model.Res
ctx.ShouldBindBodyWith(&arr, binding.JSON)
d := db.GetPG()
tx, _ := d.Begin()
for _, row := range arr.Tunits {
s := "update tunit set unitid='" + row.Unitid + "',unitname='"
s += row.Unitname + "' where unitid='" + row.Unitid + "'"
_, err := tx.Exec(s)
if err != nil {
tx.Rollback()
r.Status = 500
r.Message = "fail"
r.Exception = err.Error()
ctx.JSON(500, &r)
log.Log("UpdateUnits()", err)
return
}
}
tx.Commit()
r.Status = 200
r.Message = "success"
ctx.JSON(200, &r)
}
func DeleteUnits(ctx *gin.Context) {
var r model.Res
d := db.GetPG()
where := ctx.Param("where")
where = strings.Trim(where, "/")
s := "delete from tunit where " + where
_, err := d.Exec(s)
if err != nil {
r.Status = 500
r.Message = "fail"
r.Exception = err.Error()
ctx.JSON(500, &r)
log.Log("DeleteUnits()", err)
return
}
r.Status = 200
r.Message = "success"
ctx.JSON(200, &r)
}
Original: https://www.cnblogs.com/hnxxcxg/p/16533684.html
Author: delphi中间件
Title: gin CRUD
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/545978/
转载文章受原作者版权保护。转载请注明原作者出处!