func (c *MockRuleController) Get() { var rule models.MockRule var contents []*models.MockContent id, _ := strconv.Atoi(c.Ctx.Input.Param(":id")) o := orm.NewOrm() rule.Id = id err := o.Read(&rule) if err == orm.ErrNoRows || err == orm.ErrMissPK { c.ShowError("Can't find data.") return } rule.UnmarshalHeaderAndParams() _, err = o.QueryTable("mock_content").Filter("ruleId", id).All(&contents) rule.Contents = contents c.ShowSuccess(rule) }
func (c *MockRuleController) Toggle() { var rule models.MockRule id, _ := strconv.Atoi(c.Ctx.Input.Param(":id")) rule.Id = id o := orm.NewOrm() err := o.Read(&rule) if err == orm.ErrNoRows || err == orm.ErrMissPK { c.ShowError("Can't find data.") return } rule.Enable = !rule.Enable _, err = o.Update(&rule) if err == orm.ErrNoRows || err == orm.ErrMissPK { c.ShowError(err.Error()) return } refreshRuleCache() c.ShowSuccess(nil) }
func (c *MockRuleController) Post() { var rule models.MockRule var oldContents []*models.MockContent o := orm.NewOrm() rule.Bind(c) if rule.Url == "" { c.ShowError("Url is required") return } if rule.ProjectId <= 0 { c.ShowError("Please select a project") return } if rule.Method == "" { c.ShowError("Please select a http method") return } // save rule created, _, err := o.ReadOrCreate(&rule, "Id") if err != nil { c.ShowError(err.Error()) return } if !created { rule.Bind(c) _, err := o.Update(&rule) if err != nil { c.ShowError(err.Error()) return } } // save content contentMap := make(map[int]*models.MockContent) for _, content := range rule.Contents { contentMap[content.Id] = content } _, err = o.QueryTable("mock_content").Filter("ruleId", rule.Id).All(&oldContents) if err == nil { // detele old content && update old content for _, content := range oldContents { if newContent, found := contentMap[content.Id]; !found { o.QueryTable("mock_content").Filter("id", content.Id).Delete() } else { content.Tag = newContent.Tag content.Content = newContent.Content content.DelaySeconds = newContent.DelaySeconds o.Update(content) } } // add new content for _, content := range rule.Contents { if content.Id <= 0 { content.RuleId = rule.Id o.Insert(content) } } } o.QueryTable("mock_content").Filter("ruleId", rule.Id).All(&rule.Contents) rule.UnmarshalHeaderAndParams() refreshRuleCache() c.ShowSuccess(rule) }