本文整理汇总了Golang中github.com/dchest/uniuri.NewLen函数的典型用法代码示例。如果您正苦于以下问题:Golang NewLen函数的具体用法?Golang NewLen怎么用?Golang NewLen使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewLen函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: newToken
func newToken(db DB, user *User) (*Token, error) {
tokenId := uniuri.NewLen(20)
t, err := db.Get(Token{}, tokenId, user.UserId)
for err == nil && t != nil {
// Shit, we generated an existing token...
// just one time in 10^32
// Let's play the lottery!
tokenId := uniuri.NewLen(20)
t, err = db.Get(Token{}, tokenId, user.UserId)
}
if err != nil {
return nil, err
}
token := &Token{
TokenId: tokenId,
UserId: user.UserId,
Creation: time.Now(),
}
err = db.Insert(token)
if err != nil {
return nil, err
}
return token, nil
}
开发者ID:rafadev7,项目名称:server,代码行数:29,代码来源:auth.go
示例2: saveUrl
func saveUrl(db DB, user *User, fullUrl string) (*Url, error) {
log.Println("Starting SaveImage")
urlId := uniuri.NewLen(5)
u, err := db.Get(Url{}, urlId)
for err == nil && u != nil {
urlId := uniuri.NewLen(5)
u, err = db.Get(Url{}, urlId)
}
if err != nil {
return nil, err
}
url := &Url{
UrlId: urlId,
FullUrl: fullUrl,
UserId: user.UserId,
Creation: time.Now(),
ViewCount: 0,
}
err = db.Insert(url)
if err != nil {
return nil, err
}
return url, nil
}
开发者ID:rafadev7,项目名称:server,代码行数:28,代码来源:handlers.go
示例3: CreateContent
func CreateContent(db DB, user *User, url *Url, img *Image, content *Content) (*Content, error) {
contentId := uniuri.NewLen(20)
u, err := db.Get(Content{}, contentId)
for err == nil && u != nil {
contentId := uniuri.NewLen(20)
u, err = db.Get(Content{}, contentId)
}
if err != nil {
return nil, err
}
s := slug.Slug(content.Title)
// Let's check if this slug already exists,
// if existis, we will increment a sulfix to it
newSlug := s
increment := 1
count, err := db.SelectInt("select count(*) from content where slug=?", newSlug)
for err == nil && count != 0 {
increment += 1
newSlug = fmt.Sprintf("%s-%d", s, increment)
count, err = db.SelectInt("select count(*) from content where slug=?", newSlug)
}
log.Printf("SLUG: %s, inc: %d, count: %d\n", newSlug, increment, count)
if err != nil {
return nil, err
}
newContent := &Content{
ContentId: contentId,
UrlId: url.UrlId,
CategoryId: "default", // First category will be "Sem categoria"
Title: content.Title,
Slug: newSlug,
Description: content.Description,
Host: content.Host,
UserId: user.UserId,
ImageId: "default", // We will check the if there is an image below
LikeCount: 0,
Creation: time.Now(),
LastUpdate: time.Now(),
Deleted: false,
}
if img != nil {
newContent.ImageId = img.ImageId
}
err = db.Insert(newContent)
if err != nil {
return nil, err
}
return newContent, nil
}
开发者ID:rafadev7,项目名称:irado,代码行数:59,代码来源:content.go
示例4: newUser
func newUser(db DB, profile *Profile) (*User, error) {
userId := uniuri.NewLen(20)
userName := profile.UserName
var users []User
var increment = 0
query := "select * from user where userid=? or username=?"
_, err := db.Select(&users, query, userId, userName)
for err == nil && len(users) != 0 {
log.Printf("Trying to create another userid U[%v]: %#v \n", len(users), users)
u := users[0]
users = users[:0] // Clear my slice
// I will play in lottery if we see it happennig
// just one time in 10^32
if u.UserId == userId {
userId = uniuri.NewLen(20)
}
// If already exists an user with this userName
if u.UserName == userName {
increment += 1
userName = fmt.Sprintf("%s%d", profile.UserName, increment)
}
// Check if still existing an user like this
_, err = db.Select(&users, query, userId, userName)
}
// Checks if main loop didn't finish for an error
if err != nil {
return nil, err
}
user := &User{
UserId: userId,
UserName: userName,
PicId: "default", // Reference to default pic
FullName: profile.FullName,
LikeCount: 0,
Creation: time.Now(),
LastUpdate: time.Now(),
Deleted: false,
Admin: false,
}
err = db.Insert(user)
if err != nil {
return nil, err
}
return user, nil
}
开发者ID:rafadev7,项目名称:server,代码行数:58,代码来源:auth.go
示例5: createCluster
func createCluster(cmd *cobra.Command, args []string) {
createClusterFlags.VaultAddress = vaultCfg.VaultAddr
createClusterFlags.VaultCertificatePath = vaultCfg.VaultCACert
requireProfile := false
loadArgumentsFromCluster(cmd.Flags(), requireProfile)
clusterInfoFromArgs(&createClusterFlags.ClusterInfo, args)
provider := newProvider()
createClusterFlags = provider.CreateClusterDefaults(createClusterFlags)
// Create cluster ID if needed
if createClusterFlags.ID == "" {
createClusterFlags.ID = strings.ToLower(uniuri.NewLen(40))
} else {
createClusterFlags.ID = strings.ToLower(createClusterFlags.ID)
}
// Create weave password if needed
if createClusterFlags.WeavePassword == "" {
createClusterFlags.WeavePassword = uniuri.NewLen(40)
}
// Validate
if err := createClusterFlags.Validate(); err != nil {
Exitf("Create failed: %s\n", err.Error())
}
// See if there are already instances for the given cluster
instances, err := provider.GetInstances(createClusterFlags.ClusterInfo)
if err != nil {
Exitf("Failed to query existing instances: %v\n", err)
}
if len(instances) > 0 {
Exitf("Cluster %s.%s already exists.\n", createClusterFlags.Name, createClusterFlags.Domain)
}
// Confirm
if err := confirm(fmt.Sprintf("Are you sure you want to create a %d instance cluster of %s?", createClusterFlags.InstanceCount, createClusterFlags.InstanceConfig)); err != nil {
Exitf("%v\n", err)
}
// Create
err = provider.CreateCluster(log, createClusterFlags, newDnsProvider())
if err != nil {
Exitf("Failed to create new cluster: %v\n", err)
}
// Update all members
reboot := true
if err := providers.UpdateClusterMembers(log, createClusterFlags.ClusterInfo, reboot, nil, provider); err != nil {
Exitf("Failed to update cluster members: %v\n", err)
}
Infof("Cluster created with ID: %s\n", createClusterFlags.ID)
}
开发者ID:pulcy,项目名称:quark,代码行数:56,代码来源:cluster_create.go
示例6: getPic
// Take a http client with a transport pre-configured with the user credentials
// and return the Pic saved in public/img/pic/ and stored in DB
func getPic(db DB, client *http.Client) (*Pic, error) {
// OK WE HAVE THE PROFILE, BUT WE DON'T HAVE USER'S PICTURE
// LETS TAKE IT
res, err := client.Get("https://graph.facebook.com/me/picture")
if err != nil {
return nil, err
}
defer res.Body.Close()
img, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
picId := uniuri.NewLen(20)
p, err := db.Get(Pic{}, picId)
for err == nil && p != nil {
// Shit, we generated an existing picId!
// Lotto, where are you?
picId := uniuri.NewLen(20)
p, err = db.Get(Pic{}, picId)
}
if err != nil {
return nil, err
}
fo, err := os.Create("public/pic/" + picId + ".png")
if err != nil {
return nil, err
}
// close fo on exit and check for its returned error
defer func() {
if err := fo.Close(); err != nil {
panic(err)
}
}()
fo.Write(img)
pic := &Pic{
PicId: picId,
Creation: time.Now(),
Deleted: false,
}
err = db.Insert(pic)
if err != nil {
return nil, err
}
return pic, nil
}
开发者ID:rafadev7,项目名称:server,代码行数:57,代码来源:auth.go
示例7: create
func create(c *gin.Context) {
var err error
remote := c.ClientIP()
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, conf.C.LimitSize*1000000)
fd, h, err := c.Request.FormFile("file")
if err != nil {
log.Printf("[ERROR][%s]\tDuring reading file : %s", remote, err)
c.String(http.StatusRequestEntityTooLarge, "Entity is too large (Max : %v MB)\n", conf.C.LimitSize)
c.AbortWithStatus(http.StatusRequestEntityTooLarge)
return
}
defer fd.Close()
u := uniuri.NewLen(conf.C.UniURILength)
k := uniuri.NewLen(16)
kb := []byte(k)
block, err := aes.NewCipher(kb)
if err != nil {
log.Printf("[ERROR][%s]\tDuring Cipher creation : %s\n", remote, err)
c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
c.AbortWithStatus(http.StatusInternalServerError)
return
}
var iv [aes.BlockSize]byte
stream := cipher.NewCFBEncrypter(block, iv[:])
path := path.Join(conf.C.UploadDir, u)
file, err := os.Create(path)
if err != nil {
log.Printf("[ERROR][%s]\tDuring file creation : %s\n", remote, err)
c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
c.AbortWithStatus(http.StatusInternalServerError)
return
}
defer file.Close()
writer := &cipher.StreamWriter{S: stream, W: file}
// No encryption : wr, err := io.Copy(file, bufio.NewReaderSize(fd, 512))
// Copy the input file to the output file, encrypting as we go.
wr, err := io.Copy(writer, bufio.NewReaderSize(fd, 512))
if err != nil {
log.Printf("[ERROR][%s]\tDuring writing : %s\n", remote, err)
c.String(http.StatusInternalServerError, "Something went wrong on the server side. Try again later.")
c.AbortWithStatus(http.StatusInternalServerError)
}
db.Create(&models.ResourceEntry{Key: u, Name: h.Filename})
log.Printf("[INFO][%s]\tCreated %s file and entry (%v bytes written)\n", remote, u, wr)
c.String(http.StatusCreated, "https://%s/v/%s/%s\n", conf.C.NameServer, u, k)
}
开发者ID:krionux,项目名称:goploader,代码行数:52,代码来源:main.go
示例8: createUser
func (p *portalAPI) createUser(res http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
n := struct {
Email string
Name string
Password string
Profile map[string]interface{}
After string
}{}
if decoder.Decode(&n) != nil || n.Email == "" || n.Password == "" || n.Name == "" {
abort(res, 400, "Request a new account by supplying your email, name and password.")
return
}
u := User{Name: n.Name, Email: n.Email, Active: false, Profile: n.Profile}
err := p.m.AddUser(n.Email, n.Password, &u)
if err != nil {
abort(res, 400, "Could not create new account: %s", err.Error())
return
}
if !u.Active {
code := uniuri.NewLen(48)
act := activationData{Email: n.Email, After: n.After}
r := p.a.redis.Get()
jsonAct, _ := json.Marshal(&act)
r.Do("SETEX", "activation:"+code, (24 * time.Hour).Seconds(), jsonAct)
// TODO send activation code email
}
finish(res, &u)
}
开发者ID:fkluthe,项目名称:apiplexy,代码行数:29,代码来源:portal_api.go
示例9: NewInsert
func NewInsert(name, table string, args ...string) (Insert, error) {
conn, err := connection.Get()
if err != nil {
return Insert{}, err
}
bi := Insert{}
serial := uniuri.NewLen(5)
bi.name = fmt.Sprintf(name, serial)
bi.table = fmt.Sprintf(table, bi.name)
tx, err := conn.Begin()
if err != nil {
return bi, err
}
// close up our defer tx.Rollback()
bi.tx = tx
_, err = bi.tx.Exec(bi.table)
if err != nil {
return bi, err
}
// prepare args
for idx, i := range args {
args[idx] = fmt.Sprintf(`"%s"`, i)
}
bi.args = args
stmt := fmt.Sprintf(
`COPY %s (%s) FROM STDIN`,
bi.name,
strings.Join(bi.args, ", "),
)
bi.stmt, err = bi.tx.Prepare(stmt)
if err != nil {
return bi, err
}
return bi, nil
}
开发者ID:grunya404,项目名称:dns,代码行数:35,代码来源:bulk.go
示例10: createUser
func (p *portalAPI) createUser(res http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
n := struct {
Email string
Name string
Password string
Profile map[string]interface{}
Link string
}{}
if decoder.Decode(&n) != nil || n.Email == "" || n.Password == "" || n.Name == "" || n.Link == "" {
abort(res, 400, "Request a new account by supplying email, name, password and a template for an activation link.")
return
}
u := User{Name: n.Name, Email: n.Email, Active: false, Profile: n.Profile}
err := p.m.AddUser(n.Email, n.Password, &u)
if err != nil {
abort(res, 400, "Could not create new account: %s", err.Error())
return
}
if !u.Active {
code := uniuri.NewLen(48)
link := strings.Replace(n.Link, "CODE", code, 1)
r := p.a.redis.Get()
r.Do("SETEX", "activation:"+code, (24 * time.Hour).Seconds(), n.Email)
p.a.sendEmail(n.Email, "Activate your account", "text/plain", fmt.Sprintf(`Hi %s,
please activate your developer account by visiting this link:
%s
`, u.Name, link))
}
finish(res, &u)
}
开发者ID:12foo,项目名称:apiplexy,代码行数:33,代码来源:portal_api.go
示例11: requestResetPassword
func (p *portalAPI) requestResetPassword(res http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
rq := struct {
Email string `json:"email"`
Link string `json:"link"`
}{}
if decoder.Decode(&rq) != nil || rq.Email == "" || rq.Link == "" {
abort(res, 400, "Specify your email and a link to reset your password.")
return
}
u := p.m.GetUser(rq.Email)
if u == nil {
abort(res, 404, "User not found.")
return
}
code := uniuri.NewLen(48)
r := p.a.redis.Get()
_, err := r.Do("SETEX", "password-reset:"+code, 60*60, rq.Email)
if err != nil {
abort(res, 500, "Couldn't store your password reset request. Please contact an administrator.")
return
}
p.a.sendEmail(rq.Email, "Reset your password", "text/plain; charset=UTF-8", fmt.Sprintf(`Hi %s,
to reset your password, please visit this link:
%s
`, u.Name, strings.Replace(rq.Link, "CODE", code, 1)))
finish(res, &rq)
}
开发者ID:12foo,项目名称:apiplexy,代码行数:31,代码来源:portal_api.go
示例12: TestCard
func TestCard(t *testing.T) {
clist := []int{1, 5, 10, 30, 60, 200, 500, 1000, 10000, 60000}
n := 30
rel_err := 0.05
for _, card := range clist {
s := 0.0
for c := 0; c < n; c++ {
a, err := NewHyperLogLog(rel_err)
if err != nil {
t.Errorf("NewHyperLogLog(%v) returned an error", rel_err)
}
for i := 0; i < card; i++ {
a.Add(uniuri.NewLen(20))
}
s += a.Card()
}
z := (s/float64(n) - float64(card)) / (rel_err * float64(card) / math.Sqrt(float64(n)))
if z < -1.96 || z > 1.96 {
t.Errorf("The error rate in HyperLogLog.Card() was greater than %v", rel_err)
}
}
}
开发者ID:jlburkhead,项目名称:go-hll,代码行数:25,代码来源:hyperloglog_test.go
示例13: SetupNames
// SetupNames configured the ClusterName and InstanceName of the given options
// using the given cluster & domain name
func (o *CreateInstanceOptions) SetupNames(prefix, clusterName, domain string) {
if prefix == "" {
prefix = strings.ToLower(uniuri.NewLen(6))
}
o.ClusterName = fmt.Sprintf("%s.%s", clusterName, domain)
o.InstanceName = fmt.Sprintf("%s.%s.%s", prefix, clusterName, domain)
}
开发者ID:pulcy,项目名称:quark,代码行数:9,代码来源:create_instance_options.go
示例14: checkAndCreateCategories
func checkAndCreateCategories(db DB) {
for i, categoryName := range categoryList {
categorySlug := slug.Slug(categoryName)
count, err := db.SelectInt("select count(*) from category where categoryslug=?", categorySlug)
if err != nil {
log.Printf("Error searching for the category with categorySlug %s\n", categorySlug)
log.Println("Stopping the creation of categories")
return
}
if count == 0 {
category := &Category{
CategoryId: uniuri.NewLen(20),
CategoryName: categoryName,
CategorySlug: categorySlug,
LikeCount: 0,
}
if i == 0 { // "Sem Categoria" is my default category
category.CategoryId = "default"
}
err := db.Insert(category)
if err != nil {
log.Printf("Error when creating the category %s. %s\n", category.CategoryName, err)
} else {
log.Printf("Category %s created!\n", category.CategoryName)
}
}
}
}
开发者ID:rafadev7,项目名称:server,代码行数:28,代码来源:db.go
示例15: linkAccess
func linkAccess(url *Url, user *User) {
url.ViewCount += 1
count, err := db.Update(url)
if err != nil {
log.Printf("Error when updating the url.ViewCount. %s.\n", err)
return
}
if count != 1 {
log.Printf("Error url.ViewCount was not updated.\n", err)
return
}
access := &Access{
AccessId: uniuri.NewLen(20),
UserId: user.UserId, // Could be anonymous
UrlId: url.UrlId,
Creation: time.Now(),
}
err = db.Insert(access)
if err != nil {
log.Printf("Error when inserting the access object. %s.\n", err)
return
}
}
开发者ID:rafadev7,项目名称:server,代码行数:25,代码来源:handlers.go
示例16: GenerateTokenAndSave
func GenerateTokenAndSave(userid uint64, deviceId string, deviceType int, role int, ip string) (string, int64, error) {
// genareting
expireDate := time.Now().AddDate(0, 0, tokenExistInDays)
randStr := uniuri.NewLen(128)
tokenHash := GenerateHashFromToken(randStr)
// saving
db, err := GetDBConnection()
if err != nil {
return "", 0, err
}
stmtIns, stmtErr := db.Prepare("REPLACE INTO ml_users_tokens(userId, tokenHash, ip, role, expireAt, deviceId, deviceType) VALUES( ?, ?, ?, ?, ?, ?, ?)")
if stmtErr != nil {
return "", 0, stmtErr
}
defer stmtIns.Close()
_, err = stmtIns.Exec(userid, tokenHash, ip, uint8(role), expireDate.Unix(), deviceId, deviceType)
if err != nil {
return "", 0, err
}
return randStr, expireDate.Unix(), nil
}
开发者ID:walkline,项目名称:GoMastersLunch,代码行数:25,代码来源:Token.go
示例17: RequestIDMiddleware
func RequestIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
id := uniuri.NewLen(uniuri.UUIDLen)
GetContext(req).Set("Request-Id", id)
req.Header.Set("X-Request-Id", id)
next.ServeHTTP(rw, req)
})
}
开发者ID:mnbbrown,项目名称:engine,代码行数:8,代码来源:middleware.go
示例18: NewResourceFromForm
// NewResourceFromForm returns a new Resource instance with some fields calculated
func NewResourceFromForm(h *multipart.FileHeader, once bool, duration time.Duration) Resource {
return Resource{
Key: uniuri.NewLen(conf.C.UniURILength),
Name: h.Filename,
Once: once,
DeleteAt: time.Now().Add(duration),
}
}
开发者ID:Depado,项目名称:goploader,代码行数:9,代码来源:resources.go
示例19: PreInsert
func (t *Token) PreInsert(s gorp.SqlExecutor) error {
t.Created = milli.Timestamp(time.Now())
t.Updated = milli.Timestamp(time.Now())
t.Value = uniuri.NewLen(30)
ex := time.Now().AddDate(0, 0, 14)
t.Expiration = milli.Timestamp(ex)
return t.Validate()
}
开发者ID:nancyandrews,项目名称:MobileMainStreet,代码行数:8,代码来源:token.go
示例20: ExampleConfiguration
// ExampleConfiguration generates an ApiplexConfig struct with example values
// and the specified plugins inserted with their default configurations at
// their appropriate places in the plugin tree. This is a good starting point
// to give to the user for customization.
func ExampleConfiguration(pluginNames []string) (*ApiplexConfig, error) {
c := ApiplexConfig{
Redis: apiplexConfigRedis{
Host: "127.0.0.1",
Port: 6379,
DB: 0,
},
Quotas: map[string]apiplexQuota{
"default": apiplexQuota{
Minutes: 5,
MaxIP: 50,
MaxKey: 5000,
},
"keyless": apiplexQuota{
Minutes: 5,
MaxIP: 20,
},
},
Serve: apiplexConfigServe{
Port: 5000,
API: "/",
Upstreams: []string{"http://your-actual-api:8000/"},
PortalAPI: "/portal/api/",
Portal: "/portal/",
SigningKey: uniuri.NewLen(64),
},
}
plugins := apiplexConfigPlugins{}
for _, pname := range pluginNames {
pInfo, ok := registeredPlugins[pname]
if !ok {
return nil, fmt.Errorf("No plugin '%s' available.", pname)
}
pluginPtr := reflect.New(pInfo.pluginType)
defConfig := pluginPtr.MethodByName("DefaultConfig").Call([]reflect.Value{})[0].Interface().(map[string]interface{})
pconfig := apiplexPluginConfig{Plugin: pname, Config: defConfig}
switch pluginPtr.Interface().(type) {
case AuthPlugin:
plugins.Auth = append(plugins.Auth, pconfig)
case ManagementBackendPlugin:
plugins.Backend = append(plugins.Backend, pconfig)
case BackendPlugin:
plugins.Backend = append(plugins.Backend, pconfig)
case PreUpstreamPlugin:
plugins.PreUpstream = append(plugins.PreUpstream, pconfig)
case PostUpstreamPlugin:
plugins.PostUpstream = append(plugins.PostUpstream, pconfig)
case PostAuthPlugin:
plugins.PostAuth = append(plugins.PostAuth, pconfig)
case LoggingPlugin:
plugins.Logging = append(plugins.Logging, pconfig)
}
}
c.Plugins = plugins
return &c, nil
}
开发者ID:fkluthe,项目名称:apiplexy,代码行数:62,代码来源:build.go
注:本文中的github.com/dchest/uniuri.NewLen函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论