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) }
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/p/16533684.html