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) }