package config import ( "errors" "fmt" "regexp" "strconv" "strings" "time" ) type ( Config struct { Systems []System } System struct { Name string Db string Jobs []Job } Job struct { Name string Tasks []Task File string } Task struct { PK string Sql string Timestamp bool Elt string Order string } ) func (c Config) GetSystem(system string) (System, error) { for _, s := range c.Systems { if s.Name == system { return s, nil } } return System{}, errors.New("没有找到相关配置:" + system) } func (s System) GetJob(job string) (Job, error) { for _, j := range s.Jobs { if j.Name == job { return j, nil } } return Job{}, errors.New("没有找到相关配置:" + job) } func (t Task) GetSql(params map[string]interface{}) string { sql := t.Sql m := regexp.MustCompile("({[a-zA-Z0-9]+})") if strings.Trim(t.Elt, " ") != "" { wehre := m.ReplaceAllFunc([]byte(t.Elt), func(b []byte) []byte { field := string(b[1 : len(b)-1]) if val, ok := params[field]; ok { return []byte(t.getParam(val)) } return b }) sql = sql + " where " + string(wehre) } if strings.Trim(t.Order, " ") != "" { sql = sql + " order by " + t.Order } return sql } func (t Task) getParam(parm interface{}) string { switch p := parm.(type) { case time.Time: if t.Timestamp { return strconv.FormatInt(p.Unix(), 10) } else { return p.Format("2006-01-02 15:04:05") } case string: return p case int: return strconv.Itoa(p) case int32: return strconv.FormatInt(int64(p), 10) default: return fmt.Sprint(p) } }