//get specify week points. //@ w param specify how many weeks data to get (not include this week) func (this *Point) GetWeekPoints(w int) ([]string, interface{}) { var points []orm.Params o := orm.NewOrm() index_keys := []string{} result := make(map[string]interface{}) t := time.Now() sunday_str := this.GetSunday(t) t, _ = beego.DateParse(sunday_str, "Y-m-d") for i := w; i >= 0; i-- { last_sunday := t.AddDate(0, 0, -7*i) last_monday := last_sunday.AddDate(0, 0, -6) last_sunday = last_sunday.Add(time.Hour*time.Duration(23) + time.Minute*time.Duration(59) + time.Second*time.Duration(59)) end_time := beego.Date(last_sunday, "Y-m-d H:i:s") end_date := beego.Date(last_sunday, "Y-m-d") start_time := beego.Date(last_monday, "Y-m-d") data := make(map[string]interface{}) data["start_time"] = start_time data["end_date"] = end_date data["end_time"] = end_time data["time_str"] = start_time + "_" + end_time o.QueryTable(new(Point)).Filter("start_time__gte", start_time).Filter("end_time__lte", end_time).Filter("status", 10).Values(&points) data["point"] = points result[end_time] = data // index_keys[w-i] = end_time index_keys = append(index_keys, end_time) } return index_keys, result }
//返回当前时区的当前时间 func TimeLocal() time.Time { stime := "2006-01-02 15:04:05 -07:00 " datastring := beego.DateFormat(time.Now(), stime) rtime, _ := beego.DateParse(datastring, stime) fmt.Println(datastring, rtime) return rtime }
// create a time limit code // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string { format := "YmdHi" var start, end time.Time var startStr, endStr string if startInf == nil { // Use now time create code start = time.Now() startStr = beego.Date(start, format) } else { // use start string create code startStr = startInf.(string) start, _ = beego.DateParse(startStr, format) startStr = beego.Date(start, format) } end = start.Add(time.Minute * time.Duration(minutes)) endStr = beego.Date(end, format) // create sha1 encode string sh := sha1.New() sh.Write([]byte(data + setting.SecretKey + startStr + endStr + ToStr(minutes))) encoded := hex.EncodeToString(sh.Sum(nil)) code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded) return code }
//新增频道 func (this *Article) Create() { //Get方法 if this.methodGet { this.Data["token"] = this.token() //所属频道选项 this.Data["chs"] = channels.GetChannelSelectItems(0 /*, utils.ChNews*/) this.TplNames = this.getTplFileName("create") this.Render() return } //Post方法 //签名错误,返回重复提交错误 if this.invalidToken() { this.renderLoseToken() return } //数据模型 m := new(models.Articles) models.Extend(m, this.xm) m.Channelid, _ = this.GetInt("channelid") m.Title = this.GetString("title") m.Subtitle = this.GetString("subtitle") m.Intro = this.GetString("intro") m.Content = this.GetString("content") m.Keywords = this.GetString("keywords") m.Description = this.GetString("description") m.Author = this.GetString("author") if this.GetString("status") == "on" { m.Status = 1 } else { m.Status = 0 } if t, err := beego.DateParse(this.GetString("published"), "Y-n-j H:i:s"); err == nil { m.Published = utils.Millisecond(t) } else { m.Published = utils.Millisecond(time.Now()) } //数据合法性检验 if data, inv := this.invalidModel(m); inv { this.renderJson(data) return } //提交DDL var data interface{} _, err := articles.Add(m) if err != nil { data = utils.JsonMessage(false, "", err.Error()) } else { data = utils.JsonMessage(true, "", "") } this.renderJson(data) }
func (m *Image) DecodeToken(token string) error { number := utils.NumberDecode(token, setting.ImageLinkAlphabets) if len(number) < 9 { return fmt.Errorf("token `%s` too short <- `%s`", token, number) } if t, err := beego.DateParse(number[:8], "ymds"); err != nil { return fmt.Errorf("token `%s` date parse error <- `%s`", token, number) } else { m.Created = t } var err error m.Id, err = utils.StrTo(number[8:]).Int() if err != nil { return fmt.Errorf("token `%s` id parse error <- `%s`", token, err) } return nil }
// verify time limit code func VerifyTimeLimitCode(data string, minutes int, code string) bool { if len(code) <= 18 { return false } // split code start := code[:12] lives := code[12:18] if d, err := StrTo(lives).Int(); err == nil { minutes = d } // right active code retCode := CreateTimeLimitCode(data, minutes, start) if retCode == code && minutes > 0 { // check time is expired or not before, _ := beego.DateParse(start, "YmdHi") now := time.Now() if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() { return true } } return false }
// parse request.Form values to form func ParseForm(form interface{}, values url.Values) { val := reflect.ValueOf(form) elm := reflect.Indirect(val) panicAssertStructPtr(val) outFor: for i := 0; i < elm.NumField(); i++ { f := elm.Field(i) fT := elm.Type().Field(i) fName := fT.Name for _, v := range strings.Split(fT.Tag.Get("form"), ";") { v = strings.TrimSpace(v) if v == "-" { continue outFor } else if i := strings.Index(v, "("); i > 0 && strings.Index(v, ")") == len(v)-1 { tN := v[:i] v = strings.TrimSpace(v[i+1 : len(v)-1]) switch tN { case "name": fName = v } } } value := "" var vs []string if v, ok := values[fName]; ok { vs = v if len(v) > 0 { value = v[0] } } switch fT.Type.Kind() { case reflect.Bool: b, _ := StrTo(value).Bool() f.SetBool(b) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: x, _ := StrTo(value).Int64() f.SetInt(x) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: x, _ := StrTo(value).Uint64() f.SetUint(x) case reflect.Float32, reflect.Float64: x, _ := StrTo(value).Float64() f.SetFloat(x) case reflect.Struct: if fT.Type.String() == "time.Time" { if len(value) > 10 { t, err := beego.DateParse(value, setting.DateTimeFormat) if err != nil { continue } f.Set(reflect.ValueOf(t)) } else { t, err := beego.DateParse(value, setting.DateFormat) if err != nil { continue } f.Set(reflect.ValueOf(t)) } } case reflect.String: f.SetString(value) case reflect.Slice: f.Set(reflect.ValueOf(vs)) } } }
func (d *DocRoot) makeFileNode(path string) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() relPath, _ := filepath.Rel(d.Path, path) docDir := d.getDirNode(filepath.Dir(relPath)) var bingo bool var doc *DocNode rd := bufio.NewReader(file) no := 0 for { line, _, err := rd.ReadLine() if err == io.EOF { break } if no > 3 && !bingo { break } if no > 20 && bingo { return fmt.Errorf("document %s not contained ended tag `---`", path) } data := string(bytes.TrimSpace(line)) if len(data) == 3 && data == "---" { if bingo { if doc.root { if len(docDir.FilePath) > 0 { return fmt.Errorf("node %s has a document %s, can not replicate by %s", docDir.Path, docDir.FilePath, path) } docDir.Name = doc.Name docDir.Date = doc.Date docDir.Link = doc.Link docDir.Sort = doc.Sort mFor: for { l, _, er := rd.ReadLine() if er != nil { break mFor } if len(bytes.TrimSpace(l)) > 0 { docDir.FilePath = path break mFor } } if len(docDir.Link) == 0 { docDir.Link = docDir.RelPath + "/" } docDir.FileRelPath = relPath doc = docDir } else { doc.RelPath = relPath doc.FilePath = path if len(doc.Link) == 0 { doc.Link = doc.RelPath // doc.Link = strings.TrimSuffix(doc.RelPath, filepath.Ext(doc.RelPath)) } docDir.Docs = append(docDir.Docs, doc) } if dc, ok := d.links[doc.Link]; ok { return fmt.Errorf("document %s's link %s is already used by %s", path, doc.Link, dc.Path) } d.links[doc.Link] = doc break } doc = new(DocNode) doc.Path = path doc.Root = d doc.Parent = docDir bingo = true } if bingo { parts := strings.SplitN(data, ":", 2) if len(parts) == 2 { name := strings.TrimSpace(parts[0]) value := strings.TrimSpace(parts[1]) switch name { case "root": doc.root, _ = strconv.ParseBool(value) case "name": doc.Name = value case "date": doc.Date, err = beego.DateParse(value, "Y-m-d H:i") if err != nil { return err } case "link": doc.Link = value case "sort": n, _ := strconv.ParseInt(value, 10, 64) doc.Sort = int(n) } } } } return nil }
//修改账户信息 func (this *Article) Edit() { //Get方法 if this.methodGet { this.Data["token"] = this.token() id, err := this.getParamsInt64(":id") if err != nil { this.errorHandle(utils.JsonMessage(false, "invalidRequestParams", this.lang("invalidRequestParams"))) return } c, err := articles.Get(id) if err != nil { this.errorHandle(utils.JsonMessage(false, "", err.Error())) return } this.Data["article"] = c //所属频道选项 //this.Data["chs"] = channels.GetChannelSelectItems(-1, utils.ChNews, c.Channelid) this.Data["chs"] = channels.GetChannelSelectItems(0, -1, c.Channelid) this.TplNames = this.getTplFileName("edit") this.Render() return } //Post方法 //签名错误,返回重复提交错误 if this.invalidToken() { this.renderLoseToken() return } //提交DDL var data interface{} id, err := this.GetInt("id") if err != nil || id == 0 { this.errorHandle(utils.JsonMessage(false, "invalidRequestParams", this.lang("invalidRequestParams"))) return } //获取原始数据模型 m, err := articles.Get(id) if err != nil { this.errorHandle(utils.JsonMessage(false, "", err.Error())) return } //赋值 m.Channelid, _ = this.GetInt("channelid") m.Title = this.GetString("title") m.Subtitle = this.GetString("subtitle") m.Intro = this.GetString("intro") m.Content = this.GetString("content") m.Keywords = this.GetString("keywords") m.Description = this.GetString("description") m.Author = this.GetString("author") m.Updated = this.xm.Updated m.Updator = this.xm.Updator m.Ip = this.xm.Ip if this.GetString("status") == "on" { m.Status = 1 } else { m.Status = 0 } if t, err := beego.DateParse(this.GetString("published"), "Y-n-j"); err == nil { m.Published = utils.Millisecond(t) } else { m.Published = utils.Millisecond(time.Now()) } //数据合法性检验 if data, inv := this.invalidModel(m); inv { this.renderJson(data) return } //提交DDL _, err = articles.Update(m) if err != nil { data = utils.JsonMessage(false, "", err.Error()) } else { data = utils.JsonMessage(true, "", "") } this.renderJson(data) }
//返回当前时区的当前时间 func DateLocal() time.Time { sdate := "2006-01-02" datastring := beego.DateFormat(time.Now(), sdate) rtime, _ := beego.DateParse(datastring, sdate) return rtime }