一. 需求分析
- 从 02资料/章节212商品新增 中把资源拷贝到项目中
- 商品新增时需要新增的是两个表的数据tb_item和tb_item_desc表(tb_item_param规格参数暂时不考虑),在本小节中只新增tb_item表中数据,下一小节新增商品描述
- 新增成功后服务端返回EgoResult对应的json数据
- 页面接收数据后判断,如果Status为200,清空页面数据.
二.代码演示
- 在TbItemDao.go中编写函数实现对tb_item表的新增
//新增func insertItemDao(t TbItem) int{ count,err:=commons.Dml("insert into tb_item values(?,?,?,?,?,?,?,?,?,?,?)",t.Id,t.Title,t.SellPoint,t.Price,t.Num,t.Barcode,t.Image,t.Cid,t.Status,t.Created,t.Updated) if err!=nil{ return -1 } return int(count)}
- 在commons文件夹下新建Commons.go文件,并编写工具函数,实现生成主键
package commonsimport ( "time" "math/rand" "strconv")//生成数据库主键func GenId() int{ rand.Seed(time.Now().UnixNano()) id,_:=strconv.Atoi(strconv.Itoa(rand.Intn(10000))+strconv.Itoa(int(time.Now().Unix()))) return id}
- 在TbItemService.go中编写业务实现商品新增
//商品新增func insetService(f url.Values) (e commons.EgoResult){ var t TbItem cid,_:=strconv.Atoi(f["Cid"][0]) t.Cid =cid t.Title = f["Title"][0] t.SellPoint = f["SellPoint"][0] price,_:=strconv.Atoi(f["Price"][0]) t.Price = price num,_:=strconv.Atoi(f["Num"][0]) t.Num=num t.Image = f["Image"][0] t.Status = 1 date:=time.Now().Format("2006-01-02 15:04:05") t.Created =date t.Updated = date id:=commons.GenId() t.Id = id count :=insertItemDao(t) if count>0{ e.Status = 200 } return}
- 在TbItemController.go中添加函数实现商品新增,并添加映射
//商品新增func insertControllew (w http.ResponseWriter, r *http.Request) { //需要先进行解析 r.ParseForm() er:=insetService(r.Form) b,_:=json.Marshal(er) w.Header().Set(commons.HEADER_CONTENT_TYPE,commons.JSON_HEADER) w.Write(b)}func ItemHandler() { commons.Router.HandleFunc("/showItem", showItemController) commons.Router.HandleFunc("/item/delete", delByIdsController) commons.Router.HandleFunc("/item/instock", instockController) commons.Router.HandleFunc("/item/offstock", offstockController) commons.Router.HandleFunc("/item/imageupload", imagesUploadController) commons.Router.HandleFunc("/item/add", insertControllew) //商品新增}