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

Golang uuid.NewV4函数代码示例

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

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



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

示例1: setupIDs

func (s *Server) setupIDs() error {
	clusterIDPath := filepath.Join(s.dataDir, clusterIDFilename)
	clusterID, err := s.readID(clusterIDPath)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	if clusterID == "" {
		clusterID = uuid.NewV4().String()
		s.writeID(clusterIDPath, clusterID)
	}
	s.ClusterID = clusterID

	serverIDPath := filepath.Join(s.dataDir, serverIDFilename)
	serverID, err := s.readID(serverIDPath)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	if serverID == "" {
		serverID = uuid.NewV4().String()
		s.writeID(serverIDPath, serverID)
	}
	s.ServerID = serverID

	return nil
}
开发者ID:md14454,项目名称:kapacitor,代码行数:25,代码来源:server.go


示例2: Example

func Example() {
	saver := new(savers.FileSystemSaver)
	saver.Report = true
	saver.Duration = time.Second * 3

	// Run before any v1 or v2 UUIDs to ensure the saver takes
	uuid.RegisterSaver(saver)

	u1 := uuid.NewV1()
	fmt.Printf("version %d variant %x: %s\n", u1.Version(), u1.Variant(), u1)

	uP, _ := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	u3 := uuid.NewV3(uP, uuid.Name("test"))

	u4 := uuid.NewV4()
	fmt.Printf("version %d variant %x: %s\n", u4.Version(), u4.Variant(), u4)

	u5 := uuid.NewV5(uuid.NamespaceURL, uuid.Name("test"))

	if uuid.Equal(u1, u3) {
		fmt.Printf("Will never happen")
	}

	fmt.Print(uuid.Sprintf(uuid.CurlyHyphen, u5))

	uuid.SwitchFormat(uuid.BracketHyphen)
}
开发者ID:wutaizeng,项目名称:kapacitor,代码行数:27,代码来源:integration_test.go


示例3: Test_AllEnvelopes

func (s *EnvelopeRepositorySuite) Test_AllEnvelopes() {
	e1 := gledger.Envelope{
		UUID:    uuid.NewV4().String(),
		Name:    "Test Envelope 1",
		Type:    "income",
		Balance: 10,
	}
	e2 := gledger.Envelope{
		UUID: uuid.NewV4().String(),
		Name: "Test Envelope 2",
		Type: "expense",
	}
	s.mustExec(`INSERT INTO envelopes VALUES (
		$1, $2, '2016-08-30T00:00:00Z', now(), $3
	)`, e1.UUID, e1.Name, e1.Type)
	s.mustExec(`INSERT INTO envelopes VALUES (
		$1, $2, '2016-08-30T00:00:01Z', now(), $3
	)`, e2.UUID, e2.Name, e2.Type)
	s.mustExec(`INSERT INTO transactions VALUES ($1, $2, now(), 'payee', 10, 'f', 'f', now(), now(), $3)`, uuid.NewV4(), "cadd0722-6fd1-47ff-b390-b53307cc8c01", e1.UUID)

	es, err := AllEnvelopes(s.tx.Query)()
	if s.NoError(err) {
		s.Equal([]gledger.Envelope{e1, e2}, es)
	}
}
开发者ID:gledger,项目名称:api,代码行数:25,代码来源:envelope_repository_test.go


示例4: InsertPost

func InsertPost(title []byte, slug string, markdown []byte, html []byte, featured bool, isPage bool, published bool, image []byte, created_at time.Time, created_by int64) (int64, error) {

	status := "draft"
	if published {
		status = "published"
	}
	writeDB, err := readDB.Begin()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	var result sql.Result
	if published {
		result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, created_at, created_by)
	} else {
		result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, nil, nil)
	}
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	postId, err := result.LastInsertId()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	return postId, writeDB.Commit()
}
开发者ID:itkpi,项目名称:journey,代码行数:28,代码来源:insertion.go


示例5: TestProcessCancelCommandMessage

// TestProcessCancelCommandMessage tests that processCancelCommandMessage calls all the expected APIs
// on receiving a cancel message.
func TestProcessCancelCommandMessage(t *testing.T) {
	testCase := TestCaseCancelCommand{
		MsgToCancelID: uuid.NewV4().String(),
		MsgID:         uuid.NewV4().String(),
		InstanceID:    "i-400e1090",
	}

	testProcessCancelCommandMessage(t, testCase)
}
开发者ID:aws,项目名称:amazon-ssm-agent,代码行数:11,代码来源:processor_test.go


示例6: TestTrak

// For now, it doesn't actually test much to be honest
func TestTrak(t *testing.T) {
	log.Printf("### TRAK.TRANSACTION")

	tr := &Transaction{
		ID:        uuid.NewV4().String(),
		Timestamp: time.Now(),
		Author:    uuid.NewV4().String(),
		Action:    "buy food and eat",
		Payload: []Payload{
			Payload{
				ID:     uuid.NewV4().String(),
				Table:  "transactions",
				Action: "insert",
				Values: map[string]interface{}{
					"timestamp": time.Now(),
					"item":      uuid.NewV4().String(),
					"buyer":     uuid.NewV4().String(),
				},
			},
			Payload{
				ID:     uuid.NewV4().String(),
				Table:  "accounts",
				Action: "update",
				Values: map[string]interface{}{
					"money": 23712,
				},
			},
			Payload{
				ID:     uuid.NewV4().String(),
				Table:  "accounts",
				Action: "update",
				Values: map[string]interface{}{
					"money": 82139,
				},
			},
			Payload{
				ID:     uuid.NewV4().String(),
				Table:  "players",
				Action: "update",
				Values: map[string]interface{}{
					"hunger":    0,
					"last_meal": time.Now(),
				},
			},
			Payload{
				ID:     uuid.NewV4().String(),
				Table:  "items",
				Action: "delete",
			},
		},
	}

	trJ, _ := tr.JSON()
	log.Printf("Transaction JSON: %s", trJ)

	trS, _, _ := tr.SQL()
	log.Printf("Transaction SQL: %s", trS)
}
开发者ID:kkaribu,项目名称:trak,代码行数:59,代码来源:trak_test.go


示例7: generateKey

func generateKey() (string, string, error) {
	key := uuid.NewV4().String()
	secretKey := uuid.NewV4().String()
	_, err := Conn.Do("SADD", "api-keys", key)
	if err != nil {
		return "", "", err
	}
	_, err = Conn.Do("HSET", "key:"+key, "secret", secretKey)
	if err != nil {
		return "", "", err
	}
	_, err = Conn.Do("SADD", "key:"+key+":permissions", GetPermission, UploadPermission)
	return key, secretKey, err
}
开发者ID:EikeDawid,项目名称:pixlserv,代码行数:14,代码来源:auth.go


示例8: Initialize

func Initialize() error {
	// If journey.db does not exist, look for a Ghost database to convert
	if !helpers.FileExists(filenames.DatabaseFilename) {
		// Convert Ghost database if available (time format needs to change to be compatible with journey)
		migration.Ghost()
	}
	// Open or create database file
	var err error
	readDB, err = sql.Open("sqlite3", filenames.DatabaseFilename)
	if err != nil {
		return err
	}
	readDB.SetMaxIdleConns(256) // TODO: is this enough?
	err = readDB.Ping()
	if err != nil {
		return err
	}
	currentTime := time.Now()
	_, err = readDB.Exec(stmtInitialization, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime)
	// TODO: Is Commit()/Rollback() needed for DB.Exec()?
	if err != nil {
		return err
	}
	err = checkBlogSettings()
	if err != nil {
		return err
	}
	return nil
}
开发者ID:itkpi,项目名称:journey,代码行数:29,代码来源:initialization.go


示例9: saveImage

func saveImage(image string) (string, error) {
	if image == "" {
		return "", nil
	}

	var number = uuid.NewV4()
	var newImage = "download/" + uuid.Formatter(number, uuid.CurlyHyphen)
	out, error := os.Create(newImage)
	if error != nil {
		return "", error
	}
	defer out.Close()

	response, error := http.Get(image)
	if error != nil {
		return "", error
	}
	defer response.Body.Close()

	pix, error := ioutil.ReadAll(response.Body)
	if error != nil {
		return "", error
	}

	_, error = io.Copy(out, bytes.NewReader(pix))
	if error != nil {
		return "", error
	}

	return newImage, nil
}
开发者ID:fishedee,项目名称:GoSample,代码行数:31,代码来源:main.go


示例10: NewStatistics

// NewStatistics creates an expvar-based map. Within there "name" is the Measurement name, "tags" are the tags,
// and values are placed at the key "values".
// The "values" map is returned so that statistics can be set.
func NewStatistics(name string, tags map[string]string) (string, *kexpvar.Map) {
	key := uuid.NewV4().String()

	m := &kexpvar.Map{}
	m.Init()

	// Set the name
	nameVar := &kexpvar.String{}
	nameVar.Set(name)
	m.Set("name", nameVar)

	// Set the tags
	tagsVar := &kexpvar.Map{}
	tagsVar.Init()
	for k, v := range tags {
		value := &kexpvar.String{}
		value.Set(v)
		tagsVar.Set(k, value)
	}
	m.Set("tags", tagsVar)

	// Create and set the values entry used for actual stats.
	statMap := &kexpvar.Map{}
	statMap.Init()
	m.Set("values", statMap)

	// Set new statsMap on the top level map.
	stats.Set(key, m)

	return key, statMap
}
开发者ID:wutaizeng,项目名称:kapacitor,代码行数:34,代码来源:global_stats.go


示例11: ParseMessage

func ParseMessage(recipients []string, sender string, data []byte) (msg Msg, err error) {

	msg.Sender, err = ParseAddress(sender)
	if err != nil {
		return msg, err
	}
	for _, rcpt := range recipients {
		rcptAddr, err := ParseAddress(rcpt)
		if err != nil {
			return msg, err
		}
		msg.Rcpt = append(msg.Rcpt, rcptAddr)
	}
	message, err := mail.ReadMessage(bytes.NewReader(data))
	if err != nil {
		return msg, err
	}
	msg.Message = *message

	msg.MessageId = msg.Message.Header.Get("message-id")
	if msg.MessageId == "" {
		id := uuid.NewV4()
		uuid.SwitchFormat(uuid.Clean)
		msg.MessageId = id.String()
	}

	msg.RcptDomains = make(map[string]int)
	for _, d := range msg.Rcpt {
		msg.RcptDomains[d.Domain] = msg.RcptDomains[d.Domain] + 1
	}
	return msg, nil
}
开发者ID:mehulsbhatt,项目名称:smtprelay,代码行数:32,代码来源:message.go


示例12: BenchmarkNewV4

func BenchmarkNewV4(b *testing.B) {
	for i := 0; i < b.N; i++ {
		uuid.NewV4()
	}
	b.StopTimer()
	b.ReportAllocs()
}
开发者ID:wutaizeng,项目名称:kapacitor,代码行数:7,代码来源:benchmarks_test.go


示例13: Create

func (as accountService) Create(a Account) (Account, error) {
	if a.UUID == "" {
		a.UUID = uuid.NewV4().String()
	}

	return a, as.saveAccount(a)
}
开发者ID:gledger,项目名称:api,代码行数:7,代码来源:account.go


示例14: Create

func (ts transactionService) Create(t Transaction) (Transaction, error) {
	if t.UUID == "" {
		t.UUID = uuid.NewV4().String()
	}

	return t, ts.saveTransaction(t)
}
开发者ID:gledger,项目名称:api,代码行数:7,代码来源:transaction.go


示例15: handleUpload

// Handles upload requests.
func handleUpload(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	// parse HTML template
	t, err := template.New("presign").Parse(htmlDocument)
	if err != nil {
		c.Errorf("Error parsing template: %s", err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	// a unique key to upload
	id := uuid.NewV4().String()

	// AWS S3 credentials
	creds := &s3.Credentials{
		Region:          regionName,
		Bucket:          bucketName,
		AccessKeyID:     accessKeyID,
		SecretAccessKey: secretAccessKey,
	}

	// create pre-signed POST details
	opts := &s3.PolicyOptions{5, 1024000}
	post, err := s3.NewPresignedPOST(id, creds, opts)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	// render HTML form
	t.Execute(w, post)
}
开发者ID:murrekatt,项目名称:go-aws-s3-presigned-post-app-engine,代码行数:32,代码来源:handler.go


示例16: doServerBeat

func doServerBeat(kapi client.KeysAPI) {
	var key = runningbase + *serverbeatname

	myuuid := uuid.NewV4()
	uuidstring := myuuid.String()

	fmt.Println("Badum")
	_, err := kapi.Set(context.TODO(), key, uuidstring, &client.SetOptions{PrevExist: client.PrevNoExist, TTL: time.Second * 60})
	if err != nil {
		log.Fatal(err)
	}

	running := true
	counter := *serverbeatcount

	for running {
		time.Sleep(time.Second * time.Duration(*serverbeattime))
		fmt.Println("Badum")
		_, err := kapi.Set(context.TODO(), key, uuidstring, &client.SetOptions{PrevExist: client.PrevExist, TTL: time.Second * 60, PrevValue: uuidstring})
		if err != nil {
			log.Fatal(err)
		}
		if *serverbeatcount != 0 {
			counter = counter - 1
			if counter == 0 {
				running = false
			}
		}
	}

	_, err = kapi.Delete(context.TODO(), key, &client.DeleteOptions{PrevValue: uuidstring})
	if err != nil {
		log.Fatal(err)
	}
}
开发者ID:compose-ex,项目名称:examplco2,代码行数:35,代码来源:examplco2.go


示例17: NewStatistics

// NewStatistics creates an expvar-based map. Within there "name" is the Measurement name, "tags" are the tags,
// and values are placed at the key "values".
// The "values" map is returned so that statistics can be set.
func NewStatistics(name string, tags map[string]string) *expvar.Map {
	expvarMu.Lock()
	defer expvarMu.Unlock()

	key := uuid.NewV4().String()

	m := &expvar.Map{}
	m.Init()
	expvar.Publish(key, m)

	// Set the name
	nameVar := &expvar.String{}
	nameVar.Set(name)
	m.Set("name", nameVar)

	// Set the tags
	tagsVar := &expvar.Map{}
	tagsVar.Init()
	for k, v := range tags {
		value := &expvar.String{}
		value.Set(v)
		tagsVar.Set(k, value)
	}
	m.Set("tags", tagsVar)

	// Create and set the values entry used for actual stats.
	statMap := &expvar.Map{}
	statMap.Init()
	m.Set("values", statMap)

	return statMap
}
开发者ID:md14454,项目名称:kapacitor,代码行数:35,代码来源:stats.go


示例18: NewNode

func NewNode(controllerUrl string, dockerUrl string, tlsConfig *tls.Config, cpus float64, memory float64, heartbeatInterval int, ip string, showOnlyGridContainers bool, enableDebug bool) (*Node, error) {
	if enableDebug {
		log.SetLevel(log.DebugLevel)
	}

	u := uuid.NewV4()
	id := uuid.Formatter(u, uuid.CleanHyphen)

	client, err := dockerclient.NewDockerClient(dockerUrl, tlsConfig)
	if err != nil {
		return nil, err
	}

	node := &Node{
		Id:                     id,
		client:                 client,
		controllerUrl:          controllerUrl,
		heartbeatInterval:      heartbeatInterval,
		showOnlyGridContainers: showOnlyGridContainers,
		ip:     ip,
		Cpus:   cpus,
		Memory: memory,
	}
	return node, nil
}
开发者ID:carriercomm,项目名称:docker-grid,代码行数:25,代码来源:node.go


示例19: NewEntry

func NewEntry() *Entry {
	id := uuid.NewV4()

	return &Entry{
		uuid: strings.ToUpper(uuid.Formatter(id, uuid.Clean)), // e.g. FF755C6D7D9B4A5FBC4E41C07D622C65
	}
}
开发者ID:booyaa,项目名称:go-dayone,代码行数:7,代码来源:entry.go


示例20: NewTask

/*
NewTask creates a new task with the assigned parents. The new task is in an
incomplete state, with no subtasks of it's own. Passing in nil or an empty
array as the argument for parent means it has no parent(s) and so it
is a root task.
*/
func NewTask(name string, parents []*Task) *Task {
	if parents == nil {
		parents = make([]*Task, 0)
	}

	now := time.Now().Unix()

	newTask := &Task{
		ID:           uuid.NewV4().String(),
		Name:         name,
		Complete:     false,
		CreatedDate:  now,
		ModifiedDate: now,
		DueDate:      0,
		Categories:   make([]string, 0),
		Parents:      parents,
		Subtasks:     make([]*Task, 0),
	}

	for _, parent := range parents {
		parent.AddSubtask(newTask)
	}

	return newTask
}
开发者ID:jeffbmartinez,项目名称:todo-persistence,代码行数:31,代码来源:task.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang uuid.UUID类代码示例发布时间:2022-05-28
下一篇:
Golang uuid.Formatter函数代码示例发布时间: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