• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang com.ToStr函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/Unknwon/com.ToStr函数的典型用法代码示例。如果您正苦于以下问题:Golang ToStr函数的具体用法?Golang ToStr怎么用?Golang ToStr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了ToStr函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: updateHistory

// updateHistory updates browser history.
func updateHistory(ctx *middleware.Context, id int64) {
	pairs := make([]string, 1, 10)
	pairs[0] = com.ToStr(id) + ":" + com.ToStr(time.Now().UTC().Unix())

	count := 0
	for _, pair := range strings.Split(ctx.GetCookie("user_history"), "|") {
		infos := strings.Split(pair, ":")
		if len(infos) != 2 {
			continue
		}

		pid := com.StrTo(infos[0]).MustInt64()
		if pid == 0 || pid == id {
			continue
		}

		pairs = append(pairs, pair)

		count++
		if count == 9 {
			break
		}
	}
	ctx.SetCookie("user_history", strings.Join(pairs, "|"), 9999999)
}
开发者ID:qiancy,项目名称:gowalker,代码行数:26,代码来源:docs.go


示例2: GetUserIssueStats

// GetUserIssueStats returns issue statistic information for dashboard by given conditions.
func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int) *IssueStats {
	stats := &IssueStats{}
	issue := new(Issue)
	stats.AssignCount, _ = x.Where("assignee_id=?", uid).And("is_closed=?", false).Count(issue)
	stats.CreateCount, _ = x.Where("poster_id=?", uid).And("is_closed=?", false).Count(issue)

	queryStr := "SELECT COUNT(*) FROM `issue` "
	baseCond := " WHERE issue.is_closed=?"
	if repoID > 0 {
		baseCond += " AND issue.repo_id=" + com.ToStr(repoID)
	} else {
		baseCond += " AND issue.repo_id IN (" + strings.Join(base.Int64sToStrings(repoIDs), ",") + ")"
	}
	switch filterMode {
	case FM_ASSIGN:
		baseCond += " AND assignee_id=" + com.ToStr(uid)

	case FM_CREATE:
		baseCond += " AND poster_id=" + com.ToStr(uid)
	}

	results, _ := x.Query(queryStr+baseCond, false)
	stats.OpenCount = parseCountResult(results)
	results, _ = x.Query(queryStr+baseCond, true)
	stats.ClosedCount = parseCountResult(results)
	return stats
}
开发者ID:BitSchupser,项目名称:gogs,代码行数:28,代码来源:issue.go


示例3: DeleteWikiPage

func (repo *Repository) DeleteWikiPage(doer *User, title string) (err error) {
	wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
	defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))

	localPath := repo.LocalWikiPath()
	if err = discardLocalWikiChanges(localPath); err != nil {
		return fmt.Errorf("discardLocalWikiChanges: %v", err)
	} else if err = repo.UpdateLocalWiki(); err != nil {
		return fmt.Errorf("UpdateLocalWiki: %v", err)
	}

	title = ToWikiPageName(title)
	filename := path.Join(localPath, title+".md")
	os.Remove(filename)

	message := "Delete page '" + title + "'"

	if err = git.AddChanges(localPath, true); err != nil {
		return fmt.Errorf("AddChanges: %v", err)
	} else if err = git.CommitChanges(localPath, message, doer.NewGitSig()); err != nil {
		return fmt.Errorf("CommitChanges: %v", err)
	} else if err = git.Push(localPath, "origin", "master"); err != nil {
		return fmt.Errorf("Push: %v", err)
	}

	return nil
}
开发者ID:CarloQ,项目名称:gogs,代码行数:27,代码来源:wiki.go


示例4: RelAvatarLink

func (u *User) RelAvatarLink() string {
	defaultImgUrl := "/img/avatar_default.jpg"
	if u.Id == -1 {
		return defaultImgUrl
	}

	switch {
	case u.UseCustomAvatar:
		if !com.IsExist(u.CustomAvatarPath()) {
			return defaultImgUrl
		}
		return "/avatars/" + com.ToStr(u.Id)
	case setting.DisableGravatar, setting.OfflineMode:
		if !com.IsExist(u.CustomAvatarPath()) {
			if err := u.GenerateRandomAvatar(); err != nil {
				log.Error(3, "GenerateRandomAvatar: %v", err)
			}
		}

		return "/avatars/" + com.ToStr(u.Id)
	case setting.Service.EnableCacheAvatar:
		return "/avatar/" + u.Avatar
	}
	return setting.GravatarSource + u.Avatar
}
开发者ID:GoNuuts,项目名称:gogs,代码行数:25,代码来源:user.go


示例5: checkRefs

// checkRefs checks if given packages are still referencing this one.
func checkRefs(pinfo *PkgInfo) {
	var buf bytes.Buffer
	pinfo.RefNum = 0
	refIDs := strings.Split(pinfo.RefIDs, "|")
	for i := range refIDs {
		if len(refIDs[i]) == 0 {
			continue
		}

		fmt.Println(com.StrTo(refIDs[i][1:]).MustInt64())
		pkg, _ := GetPkgInfoById(com.StrTo(refIDs[i][1:]).MustInt64())
		if pkg == nil {
			continue
		}

		if strings.Index(pkg.ImportIDs, "$"+com.ToStr(pinfo.ID)+"|") == -1 {
			continue
		}

		buf.WriteString("$")
		buf.WriteString(com.ToStr(pkg.ID))
		buf.WriteString("|")
		pinfo.RefNum++
	}
	pinfo.RefIDs = buf.String()
}
开发者ID:imjerrybao,项目名称:gowalker,代码行数:27,代码来源:package.go


示例6: dumpGC

func dumpGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) {

	if gcstats.NumGC > 0 {
		lastPause := gcstats.Pause[0]
		elapsed := time.Now().Sub(startTime)
		overhead := float64(gcstats.PauseTotal) / float64(elapsed) * 100
		allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds()

		fmt.Fprintf(w, "NumGC:%d Pause:%s Pause(Avg):%s Overhead:%3.2f%% Alloc:%s Sys:%s Alloc(Rate):%s/s Histogram:%s %s %s \n",
			gcstats.NumGC,
			com.ToStr(lastPause),
			com.ToStr(avg(gcstats.Pause)),
			overhead,
			com.HumaneFileSize(memStats.Alloc),
			com.HumaneFileSize(memStats.Sys),
			com.HumaneFileSize(uint64(allocatedRate)),
			com.ToStr(gcstats.PauseQuantiles[94]),
			com.ToStr(gcstats.PauseQuantiles[98]),
			com.ToStr(gcstats.PauseQuantiles[99]))
	} else {
		// while GC has disabled
		elapsed := time.Now().Sub(startTime)
		allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds()

		fmt.Fprintf(w, "Alloc:%s Sys:%s Alloc(Rate):%s/s\n",
			com.HumaneFileSize(memStats.Alloc),
			com.HumaneFileSize(memStats.Sys),
			com.HumaneFileSize(uint64(allocatedRate)))
	}
}
开发者ID:reduxdj,项目名称:grafana,代码行数:30,代码来源:profile.go


示例7: commitsByRange

func (repo *Repository) commitsByRange(id sha1, page int) (*list.List, error) {
	stdout, stderr, err := com.ExecCmdDirBytes(repo.Path, "git", "log", id.String(),
		"--skip="+com.ToStr((page-1)*CommitsRangeSize), "--max-count="+com.ToStr(CommitsRangeSize), prettyLogFormat)
	if err != nil {
		return nil, errors.New(string(stderr))
	}
	return parsePrettyFormatLog(repo, stdout)
}
开发者ID:Janfred,项目名称:gogs,代码行数:8,代码来源:repo_commit.go


示例8: Generate

// Generate maps CSRF to each request. If this request is a Get request, it will generate a new token.
// Additionally, depending on options set, generated tokens will be sent via Header and/or Cookie.
func Generate(options ...Options) macaron.Handler {
	opt := prepareOptions(options)
	return func(ctx *macaron.Context, sess session.Store) {
		x := &csrf{
			Secret:     opt.Secret,
			Header:     opt.Header,
			Form:       opt.Form,
			Cookie:     opt.Cookie,
			CookiePath: opt.CookiePath,
			ErrorFunc:  opt.ErrorFunc,
		}
		ctx.MapTo(x, (*CSRF)(nil))

		if opt.Origin && len(ctx.Req.Header.Get("Origin")) > 0 {
			return
		}

		x.ID = "0"
		uid := sess.Get(opt.SessionKey)
		if uid != nil {
			switch uid.(type) {
			case string:
				x.ID = uid.(string)
			case int:
				x.ID = com.ToStr(uid)
			case int64:
				x.ID = com.ToStr(uid)
			}
		}

		needsNew := false
		oldUid := sess.Get(opt.oldSeesionKey)
		if oldUid == nil || oldUid.(string) != x.ID {
			needsNew = true
			sess.Set(opt.oldSeesionKey, x.ID)
		} else {
			// If cookie present, map existing token, else generate a new one.
			if val := ctx.GetCookie(opt.Cookie); len(val) > 0 {
				// FIXME: test coverage.
				x.Token = val
			} else {
				needsNew = true
			}
		}

		if needsNew {
			// FIXME: actionId.
			x.Token = GenerateToken(x.Secret, x.ID, "POST")
		}

		if opt.SetCookie {
			ctx.SetCookie(opt.Cookie, x.Token, 0, opt.CookiePath)
		}
		if opt.SetHeader {
			ctx.Resp.Header().Add(opt.Header, x.Token)
		}
	}
}
开发者ID:macaron-contrib,项目名称:csrf,代码行数:60,代码来源:csrf.go


示例9: matchSubtree

func (t *Tree) matchSubtree(globLevel int, segment, url string, params Params) (Handle, bool) {
	for i := 0; i < len(t.subtrees); i++ {
		switch t.subtrees[i].typ {
		case _PATTERN_STATIC:
			if t.subtrees[i].pattern == segment {
				if handle, ok := t.subtrees[i].matchNextSegment(globLevel, url, params); ok {
					return handle, true
				}
			}
		case _PATTERN_REGEXP:
			results := t.subtrees[i].reg.FindStringSubmatch(segment)
			if len(results)-1 != len(t.subtrees[i].wildcards) {
				break
			}

			for j := 0; j < len(t.subtrees[i].wildcards); j++ {
				params[t.subtrees[i].wildcards[j]] = results[j+1]
			}
			if handle, ok := t.subtrees[i].matchNextSegment(globLevel, url, params); ok {
				return handle, true
			}
		case _PATTERN_HOLDER:
			if handle, ok := t.subtrees[i].matchNextSegment(globLevel+1, url, params); ok {
				params[t.subtrees[i].wildcards[0]] = segment
				return handle, true
			}
		case _PATTERN_MATCH_ALL:
			if handle, ok := t.subtrees[i].matchNextSegment(globLevel+1, url, params); ok {
				params["*"+com.ToStr(globLevel)] = segment
				return handle, true
			}
		}
	}

	if len(t.leaves) > 0 {
		leaf := t.leaves[len(t.leaves)-1]
		if leaf.typ == _PATTERN_PATH_EXT {
			url = segment + "/" + url
			j := strings.LastIndex(url, ".")
			if j > -1 {
				params[":path"] = url[:j]
				params[":ext"] = url[j+1:]
			} else {
				params[":path"] = url
			}
			return leaf.handle, true
		} else if leaf.typ == _PATTERN_MATCH_ALL {
			params["*"] = segment + "/" + url
			params["*"+com.ToStr(globLevel)] = segment + "/" + url
			return leaf.handle, true
		}
	}
	return nil, false
}
开发者ID:Xetius,项目名称:grafana,代码行数:54,代码来源:tree.go


示例10: updateWikiPage

// updateWikiPage adds new page to repository wiki.
func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, message string, isNew bool) (err error) {
	wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
	defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))

	if err = repo.InitWiki(); err != nil {
		return fmt.Errorf("InitWiki: %v", err)
	}

	localPath := repo.LocalWikiPath()
	if err = discardLocalWikiChanges(localPath); err != nil {
		return fmt.Errorf("discardLocalWikiChanges: %v", err)
	} else if err = repo.UpdateLocalWiki(); err != nil {
		return fmt.Errorf("UpdateLocalWiki: %v", err)
	}

	title = ToWikiPageName(title)
	filename := path.Join(localPath, title+".md")

	// If not a new file, show perform update not create.
	if isNew {
		if com.IsExist(filename) {
			return ErrWikiAlreadyExist{filename}
		}
	} else {
		os.Remove(path.Join(localPath, oldTitle+".md"))
	}

	// SECURITY: if new file is a symlink to non-exist critical file,
	// attack content can be written to the target file (e.g. authorized_keys2)
	// as a new page operation.
	// So we want to make sure the symlink is removed before write anything.
	// The new file we created will be in normal text format.
	os.Remove(filename)

	if err = ioutil.WriteFile(filename, []byte(content), 0666); err != nil {
		return fmt.Errorf("WriteFile: %v", err)
	}

	if len(message) == 0 {
		message = "Update page '" + title + "'"
	}
	if err = git.AddChanges(localPath, true); err != nil {
		return fmt.Errorf("AddChanges: %v", err)
	} else if err = git.CommitChanges(localPath, git.CommitChangesOptions{
		Committer: doer.NewGitSig(),
		Message:   message,
	}); err != nil {
		return fmt.Errorf("CommitChanges: %v", err)
	} else if err = git.Push(localPath, "origin", "master"); err != nil {
		return fmt.Errorf("Push: %v", err)
	}

	return nil
}
开发者ID:VoyTechnology,项目名称:gogs,代码行数:55,代码来源:wiki.go


示例11: updateWikiPage

// updateWikiPage adds new page to repository wiki.
func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, message string, isNew bool) (err error) {
	wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
	defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))

	if err = repo.InitWiki(); err != nil {
		return fmt.Errorf("InitWiki: %v", err)
	}

	localPath := repo.LocalWikiPath()

	// Discard local commits make sure even to remote when local copy exists.
	if com.IsExist(localPath) {
		// No need to check if nothing in the repository.
		if git.IsBranchExist(localPath, "master") {
			if err = git.ResetHEAD(localPath, true, "origin/master"); err != nil {
				return fmt.Errorf("Reset: %v", err)
			}
		}
	}

	if err = repo.UpdateLocalWiki(); err != nil {
		return fmt.Errorf("UpdateLocalWiki: %v", err)
	}

	title = ToWikiPageName(strings.Replace(title, "/", " ", -1))
	filename := path.Join(localPath, title+".md")

	// If not a new file, show perform update not create.
	if isNew {
		if com.IsExist(filename) {
			return ErrWikiAlreadyExist{filename}
		}
	} else {
		os.Remove(path.Join(localPath, oldTitle+".md"))
	}

	if err = ioutil.WriteFile(filename, []byte(content), 0666); err != nil {
		return fmt.Errorf("WriteFile: %v", err)
	}

	if len(message) == 0 {
		message = "Update page '" + title + "'"
	}
	if err = git.AddChanges(localPath, true); err != nil {
		return fmt.Errorf("AddChanges: %v", err)
	} else if err = git.CommitChanges(localPath, message, doer.NewGitSig()); err != nil {
		return fmt.Errorf("CommitChanges: %v", err)
	} else if err = git.Push(localPath, "origin", "master"); err != nil {
		return fmt.Errorf("Push: %v", err)
	}

	return nil
}
开发者ID:cuteluo1983,项目名称:gogs,代码行数:54,代码来源:wiki.go


示例12: Put

// Put puts value into cache with key and expire time.
// If expired is 0, it lives forever.
func (c *LedisCacher) Put(key string, val interface{}, expire int64) (err error) {
	if expire == 0 {
		if err = c.c.Set([]byte(key), []byte(com.ToStr(val))); err != nil {
			return err
		}
		_, err = c.c.HSet([]byte(key), defaultHSetName, []byte("0"))
		return err
	}

	if err = c.c.SetEX([]byte(key), expire, []byte(com.ToStr(val))); err != nil {
		return err
	}
	_, err = c.c.HSet([]byte(key), defaultHSetName, []byte(com.ToStr(time.Now().Add(time.Duration(expire)*time.Second).Unix())))
	return err
}
开发者ID:kenno,项目名称:cache,代码行数:17,代码来源:ledis.go


示例13: RemoveRepository

// RemoveRepository removes repository from team of organization.
func (t *Team) RemoveRepository(repoId int64) error {
	idStr := "$" + com.ToStr(repoId) + "|"
	if !strings.Contains(t.RepoIds, idStr) {
		return nil
	}

	repo, err := GetRepositoryById(repoId)
	if err != nil {
		return err
	}

	if err = repo.GetOwner(); err != nil {
		return err
	} else if err = t.GetMembers(); err != nil {
		return err
	}

	sess := x.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return err
	}

	t.NumRepos--
	t.RepoIds = strings.Replace(t.RepoIds, idStr, "", 1)
	if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
		sess.Rollback()
		return err
	}

	// Remove access to team members.
	for _, u := range t.Members {
		auth, err := GetHighestAuthorize(t.OrgId, u.Id, repo.Id, t.Id)
		if err != nil {
			sess.Rollback()
			return err
		}

		access := &Access{
			UserName: u.LowerName,
			RepoName: path.Join(repo.Owner.LowerName, repo.LowerName),
		}
		if auth == 0 {
			if _, err = sess.Delete(access); err != nil {
				sess.Rollback()
				return fmt.Errorf("fail to delete access: %v", err)
			} else if err = WatchRepo(u.Id, repo.Id, false); err != nil {
				sess.Rollback()
				return err
			}
		} else if auth < t.Authorize {
			if err = addAccessWithAuthorize(sess, access, AuthorizeToAccessType(auth)); err != nil {
				sess.Rollback()
				return err
			}
		}
	}

	return sess.Commit()
}
开发者ID:felipelovato,项目名称:gogs,代码行数:61,代码来源:org.go


示例14: init

func init() {
	// Load data.
	if com.IsExist("data.txt") {
		data, err := ioutil.ReadFile("data.txt")
		if err != nil {
			log.Printf("Fail to load data file: %v", err)
			os.Exit(2)
		}
		if len(data) == 0 {
			log.Println("Data file cannot be empty")
			os.Exit(2)
		}
		for _, line := range strings.Split(string(data), "\n") {
			line := strings.TrimSpace(line)
			if len(line) == 0 {
				continue
			}

			infos := strings.Split(line, "\t")
			if len(infos) < 2 {
				continue
			}
			people = append(people, person{infos[0], infos[1]})
		}
	} else {
		// Generate fake data.
		s := rand.NewSource(int64(time.Now().Nanosecond()))
		r := rand.New(s)
		for i := 0; i < 100; i++ {
			info := com.ToStr(r.Int())
			people = append(people, person{info, info})
		}
	}
}
开发者ID:xormplus,项目名称:examples,代码行数:34,代码来源:lottery.go


示例15: DeleteLabel

// DeleteLabel delete a label of given repository.
func DeleteLabel(repoID, labelID int64) error {
	l, err := GetLabelById(labelID)
	if err != nil {
		if err == ErrLabelNotExist {
			return nil
		}
		return err
	}

	issues, err := GetIssuesByLabel(repoID, labelID)
	if err != nil {
		return err
	}

	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	for _, issue := range issues {
		issue.LabelIds = strings.Replace(issue.LabelIds, "$"+com.ToStr(labelID)+"|", "", -1)
		if _, err = sess.Id(issue.ID).AllCols().Update(issue); err != nil {
			return err
		}
	}

	if _, err = sess.Delete(l); err != nil {
		return err
	}
	return sess.Commit()
}
开发者ID:GOGOGO7,项目名称:gogs,代码行数:33,代码来源:issue.go


示例16: listen

func listen(config *ssh.ServerConfig, port int) {
	listener, err := net.Listen("tcp", "0.0.0.0:"+com.ToStr(port))
	if err != nil {
		panic(err)
	}
	for {
		// Once a ServerConfig has been configured, connections can be accepted.
		conn, err := listener.Accept()
		if err != nil {
			log.Error(3, "Error accepting incoming connection: %v", err)
			continue
		}
		// Before use, a handshake must be performed on the incoming net.Conn.
		sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
		if err != nil {
			log.Error(3, "Error on handshaking: %v", err)
			continue
		}

		log.Trace("Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
		// The incoming Request channel must be serviced.
		go ssh.DiscardRequests(reqs)
		go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
	}
}
开发者ID:cuteluo1983,项目名称:gogs,代码行数:25,代码来源:ssh.go


示例17: Listen

// Listen starts a SSH server listens on given port.
func Listen(port int) {
	config := &ssh.ServerConfig{
		PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
			pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
			if err != nil {
				log.Error(3, "SearchPublicKeyByContent: %v", err)
				return nil, err
			}
			return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
		},
	}

	keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
	if !com.IsExist(keyPath) {
		os.MkdirAll(filepath.Dir(keyPath), os.ModePerm)
		_, stderr, err := com.ExecCmd("ssh-keygen", "-f", keyPath, "-t", "rsa", "-N", "")
		if err != nil {
			panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))
		}
		log.Trace("New private key is generateed: %s", keyPath)
	}

	privateBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		panic("Fail to load private key")
	}
	private, err := ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		panic("Fail to parse private key")
	}
	config.AddHostKey(private)

	go listen(config, port)
}
开发者ID:cuteluo1983,项目名称:gogs,代码行数:35,代码来源:ssh.go


示例18: updatePkgRef

func updatePkgRef(pid int64, refPath string) error {
	if base.IsGoRepoPath(refPath) ||
		refPath == "C" ||
		refPath[1] == '.' {
		return nil
	}

	ref := new(PkgRef)
	has, err := x.Where("import_path=?", refPath).Get(ref)
	if err != nil {
		return fmt.Errorf("get PkgRef: %v", err)
	}

	queryStr := "$" + com.ToStr(pid) + "|"
	if !has {
		if _, err = x.Insert(&PkgRef{
			ImportPath: refPath,
			RefNum:     1,
			RefIDs:     queryStr,
		}); err != nil {
			return fmt.Errorf("insert PkgRef: %v", err)
		}
		return nil
	}

	i := strings.Index(ref.RefIDs, queryStr)
	if i > -1 {
		return nil
	}

	ref.RefIDs += queryStr
	ref.RefNum++
	_, err = x.Id(ref.ID).AllCols().Update(ref)
	return err
}
开发者ID:xushiwei,项目名称:gowalker,代码行数:35,代码来源:package.go


示例19: validateUserEmailCode

// verify time limit code
func validateUserEmailCode(user *m.User, code string) bool {
	if len(code) <= 18 {
		return false
	}

	minutes := setting.EmailCodeValidMinutes
	code = code[:timeLimitCodeLength]

	// split code
	start := code[:12]
	lives := code[12:18]
	if d, err := com.StrTo(lives).Int(); err == nil {
		minutes = d
	}

	// right active code
	data := com.ToStr(user.Id) + user.Email + user.Login + user.Password + user.Rands
	retCode := createTimeLimitCode(data, minutes, start)
	fmt.Printf("code : %s\ncode2: %s", retCode, code)
	if retCode == code && minutes > 0 {
		// check time is expired or not
		before, _ := time.ParseInLocation("200601021504", start, time.Local)
		now := time.Now()
		if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
			return true
		}
	}

	return false
}
开发者ID:dilgerma,项目名称:grafana,代码行数:31,代码来源:codes.go


示例20: AddRepository

// AddRepository adds new repository to team of organization.
func (t *Team) AddRepository(repo *Repository) (err error) {
	idStr := "$" + com.ToStr(repo.Id) + "|"
	if repo.OwnerId != t.OrgId {
		return errors.New("Repository not belong to organization")
	} else if strings.Contains(t.RepoIds, idStr) {
		return nil
	}

	if err = repo.GetOwner(); err != nil {
		return err
	} else if err = t.GetMembers(); err != nil {
		return err
	}

	sess := x.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return err
	}

	t.NumRepos++
	t.RepoIds += idStr
	if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
		sess.Rollback()
		return err
	}

	// Give access to team members.
	mode := AuthorizeToAccessType(t.Authorize)

	for _, u := range t.Members {
		auth, err := GetHighestAuthorize(t.OrgId, u.Id, t.Id, repo.Id)
		if err != nil {
			sess.Rollback()
			return err
		}

		access := &Access{
			UserName: u.LowerName,
			RepoName: path.Join(repo.Owner.LowerName, repo.LowerName),
		}
		if auth == 0 {
			access.Mode = mode
			if _, err = sess.Insert(access); err != nil {
				sess.Rollback()
				return fmt.Errorf("fail to insert access: %v", err)
			}
		} else if auth < t.Authorize {
			if err = addAccessWithAuthorize(sess, access, mode); err != nil {
				sess.Rollback()
				return err
			}
		}
		if err = WatchRepo(u.Id, repo.Id, true); err != nil {
			sess.Rollback()
			return err
		}
	}
	return sess.Commit()
}
开发者ID:hogehoge999,项目名称:gogs,代码行数:61,代码来源:org.go



注:本文中的github.com/Unknwon/com.ToStr函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang goconfig.LoadConfigFile函数代码示例发布时间:2022-05-28
下一篇:
Golang com.StrTo函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap