当前位置: 首页>>代码示例>>Golang>>正文


Golang uuid.NewUUID函数代码示例

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


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

示例1: NewSpan

func (p *platform) NewSpan(s *Span) *Span {
	if s == nil {
		// completeley new trace
		return &Span{
			Id:        uuid.NewUUID().String(),
			TraceId:   uuid.NewUUID().String(),
			ParentId:  "0",
			Timestamp: time.Now(),
			Source:    p.opts.Service,
		}
	}

	// existing trace in theory
	cp := &Span{}
	*cp = *s

	if len(s.TraceId) == 0 {
		cp.TraceId = uuid.NewUUID().String()
	}
	if len(s.ParentId) == 0 {
		cp.ParentId = "0"
	}
	if len(s.Id) == 0 {
		cp.Id = uuid.NewUUID().String()
	}
	if s.Timestamp.IsZero() {
		cp.Timestamp = time.Now()
	}
	if s.Source == nil {
		cp.Source = p.opts.Service
	}

	return cp
}
开发者ID:jelmersnoeck,项目名称:go-platform,代码行数:34,代码来源:platform.go

示例2: NewUUID

func NewUUID() string {
	uuidLock.Lock()
	defer uuidLock.Unlock()
	result := uuid.NewUUID()
	// The UUID package is naive and can generate identical UUIDs if the
	// time interval is quick enough.
	// The UUID uses 100 ns increments so it's short enough to actively
	// wait for a new value.
	for uuid.Equal(lastUUID, result) == true {
		result = uuid.NewUUID()
	}
	lastUUID = result
	return result.String()
}
开发者ID:otsimo,项目名称:listener,代码行数:14,代码来源:uuid.go

示例3: NewRule

func NewRule(title string, src string, eps []string) *Rule {
	return &Rule{
		Id:        uuid.NewUUID().String(),
		Title:     title,
		Script:    src,
		Endpoints: eps}
}
开发者ID:ashaniray,项目名称:mailhook,代码行数:7,代码来源:rule.go

示例4: BatchEnq

func BatchEnq(d []OpSend, ttl ...uint32) {
	if len(d) <= 0 {
		return
	}
	c := pool.Get()
	defer c.Close()
	for _, v := range d {
		if data, err := json.Marshal(v); err != nil {
			fmt.Println("err:", err)
		} else {
			k := fmt.Sprintf("mk%v", uuid.NewUUID())
			if len(ttl) > 0 && ttl[0] > 0 {
				if err := c.Send("SETEX", k, ttl[0], data); err != nil {
					log.Println("[Batch Q SetEx] err :", err)
				}
			} else {
				if err := c.Send("SET", k, data); err != nil {
					log.Println("[Batch Q SET] err :", err)
				}
			}
			if err := c.Send("RPUSH", OPQ_SEND, k); err != nil {
				log.Println("[Batch Q RPUSH] err :", err)
			}
		}
	}
	c.Flush()
}
开发者ID:xiaotiejiang888,项目名称:goPraticse,代码行数:27,代码来源:main.go

示例5: New

func New(ctx api.Context, id string, pod *api.Pod, prototype *mesos.ExecutorInfo, allowedRoles []string) (*T, error) {
	if prototype == nil {
		return nil, fmt.Errorf("illegal argument: executor is nil")
	}

	if len(allowedRoles) == 0 {
		allowedRoles = defaultRoles
	}

	key, err := MakePodKey(ctx, pod.Name)
	if err != nil {
		return nil, err
	}

	if id == "" {
		id = "pod." + uuid.NewUUID().String()
	}

	task := &T{
		ID:           id,
		Pod:          *pod,
		State:        StatePending,
		podKey:       key,
		mapper:       NewHostPortMapper(pod),
		Flags:        make(map[FlagType]struct{}),
		prototype:    prototype,
		allowedRoles: allowedRoles,
	}
	task.CreateTime = time.Now()

	return task, nil
}
开发者ID:fwalker,项目名称:dashboard,代码行数:32,代码来源:pod_task.go

示例6: GenerateThumbnail

// GenerateThumbnail assumes that the images have already been saved to storage,
// and that one or more image is contained within imagesValue. Returns the
// resulting filename of the generated thumbnail if successful, or an error
// otherwise.
func (imagesValue *ImagesValue) GenerateThumbnail() (string, error) {
	if !imagesValue.IsComplete() {
		return "", errors.New("No images to generate thumbnail for.")
	}
	filename := MediaDir + ThumbnailDir + uuid.NewUUID().String() + ThumbnailType
	mw := imagick.NewMagickWand()
	defer mw.Destroy()
	err := mw.ReadImage(fieldsConfig.Website.Directory + (*imagesValue)[0])
	if err != nil {
		return "", err
	}

	err = mw.ThumbnailImage(ThumbnailMaxWidth, ThumbnailMaxHeight)
	if err != nil {
		return "", err
	}

	err = mw.SetImageCompressionQuality(ThumbnailQuality)
	if err != nil {
		return "", err
	}

	err = mw.WriteImage(fieldsConfig.Website.Directory + filename)
	if err != nil {
		return "", err
	}

	return filename, nil
}
开发者ID:joshheinrichs,项目名称:geosource,代码行数:33,代码来源:images.go

示例7: newHttpBroker

func newHttpBroker(opts ...Option) Broker {
	options := Options{
		Context: context.TODO(),
	}

	for _, o := range opts {
		o(&options)
	}

	addr := ":0"
	if len(options.Addrs) > 0 && len(options.Addrs[0]) > 0 {
		addr = options.Addrs[0]
	}

	reg, ok := options.Context.Value(registryKey).(registry.Registry)
	if !ok {
		reg = registry.DefaultRegistry
	}

	h := &httpBroker{
		id:          "broker-" + uuid.NewUUID().String(),
		address:     addr,
		opts:        options,
		r:           reg,
		c:           &http.Client{Transport: newTransport(options.TLSConfig)},
		subscribers: make(map[string][]*httpSubscriber),
		unsubscribe: make(chan *httpSubscriber),
		exit:        make(chan chan error),
		mux:         http.NewServeMux(),
	}

	h.mux.Handle(DefaultSubPath, h)
	return h
}
开发者ID:ZhuJingfa,项目名称:go-micro,代码行数:34,代码来源:http_broker.go

示例8: Subscribe

func (h *httpBroker) Subscribe(topic string, handler Handler, opts ...SubscribeOption) (Subscriber, error) {
	opt := newSubscribeOptions(opts...)

	// parse address for host, port
	parts := strings.Split(h.Address(), ":")
	host := strings.Join(parts[:len(parts)-1], ":")
	port, _ := strconv.Atoi(parts[len(parts)-1])

	addr, err := extractAddress(host)
	if err != nil {
		return nil, err
	}

	id := uuid.NewUUID().String()

	var secure bool

	if h.opts.Secure || h.opts.TLSConfig != nil {
		secure = true
	}

	// register service
	node := &registry.Node{
		Id:      h.id + "." + id,
		Address: addr,
		Port:    port,
		Metadata: map[string]string{
			"secure": fmt.Sprintf("%t", secure),
		},
	}

	version := opt.Queue
	if len(version) == 0 {
		version = broadcastVersion
	}

	service := &registry.Service{
		Name:    "topic:" + topic,
		Version: version,
		Nodes:   []*registry.Node{node},
	}

	subscriber := &httpSubscriber{
		opts:  opt,
		id:    h.id + "." + id,
		topic: topic,
		ch:    h.unsubscribe,
		fn:    handler,
		svc:   service,
	}

	if err := h.r.Register(service, registry.RegisterTTL(registerTTL)); err != nil {
		return nil, err
	}

	h.Lock()
	h.subscribers[topic] = append(h.subscribers[topic], subscriber)
	h.Unlock()
	return subscriber, nil
}
开发者ID:ZhuJingfa,项目名称:go-micro,代码行数:60,代码来源:http_broker.go

示例9: main

func main() {
	log.Println("hello")
	mg := connect("192.168.56.101/figoTest")
	cp := mg.Copy()
	defer cp.Close()

	apps := map[string]string{}
	apps["com.test.com"] = "特斯特"
	apps["com.cool.me"] = "酷儿"
	apps["com.mi.me"] = "米密"

	m := &MapTest{
		Id:   bson.NewObjectId(),
		Dvid: uuid.NewUUID().String(),
		Ct:   time.Now(),
		Mt:   utee.Tick(),
		Apps: apps,
	}

	cp.DB(DB).C(C).Insert(m)

	//	func (p *Student) incTest(){
	//		if err := p.ds.DB(DB).C(C).UpdateId(p.Id, bson.M{"$inc":bson.M{"visitTimes":1}});err!=nil {
	//			log.Println("@err:",err)
	//		}
	//	}

}
开发者ID:xiaotiejiang888,项目名称:goPraticse,代码行数:28,代码来源:main.go

示例10: frameworkReregistered

func (driver *MesosSchedulerDriver) frameworkReregistered(from *upid.UPID, pbMsg proto.Message) {
	log.V(1).Infoln("Handling Scheduler re-registered event.")
	msg := pbMsg.(*mesos.FrameworkReregisteredMessage)

	if driver.status == mesos.Status_DRIVER_ABORTED {
		log.Infoln("Ignoring FrameworkReregisteredMessage from master, driver is aborted!")
		return
	}
	if driver.connected {
		log.Infoln("Ignoring FrameworkReregisteredMessage from master,driver is already connected!")
		return
	}
	if !driver.masterPid.Equal(from) {
		log.Warningf("ignoring framework re-registered message because it was sent from '%v' instead of leading master '%v'", from, driver.masterPid)
		return
	}

	// TODO(vv) detect if message was from leading-master (sched.cpp)
	log.Infof("Framework re-registered with ID [%s] ", msg.GetFrameworkId().GetValue())
	driver.connected = true
	driver.failover = false
	driver.connection = uuid.NewUUID()

	driver.withScheduler(func(s Scheduler) { s.Reregistered(driver, msg.GetMasterInfo()) })

}
开发者ID:basho-labs,项目名称:mesos-go,代码行数:26,代码来源:scheduler.go

示例11: Create

func (s *Account) Create(ctx context.Context, req *account.CreateRequest, rsp *account.CreateResponse) error {
	// validate incoming
	if err := validateAccount(req.Account, "Create"); err != nil {
		return err
	}

	// set a uuid if we dont have one
	if len(req.Account.Id) == 0 {
		req.Account.Id = uuid.NewUUID().String()
	}

	// hash the pass
	salt := db.Salt()
	h, err := bcrypt.GenerateFromPassword([]byte(x+salt+req.Account.ClientSecret), 10)
	if err != nil {
		return errors.InternalServerError("go.micro.srv.auth.Create", err.Error())
	}
	pp := base64.StdEncoding.EncodeToString(h)

	// to lower
	req.Account.ClientId = strings.ToLower(req.Account.ClientId)
	req.Account.Type = strings.ToLower(req.Account.Type)

	if err := db.Create(req.Account, salt, pp); err != nil {
		return errors.InternalServerError("go.micro.srv.auth.Create", err.Error())
	}
	return nil
}
开发者ID:micro,项目名称:auth-srv,代码行数:28,代码来源:account.go

示例12: run

// run healthchecker
func (s *Sidecar) run(exit chan bool) {
	parts := strings.Split(s.address, ":")
	host := strings.Join(parts[:len(parts)-1], ":")
	port, _ := strconv.Atoi(parts[len(parts)-1])

	id := s.name + "-" + uuid.NewUUID().String()
	node := &registry.Node{
		Id:      id,
		Address: host,
		Port:    port,
	}

	service := &registry.Service{
		Name:  s.name,
		Nodes: []*registry.Node{node},
	}

	log.Printf("Registering %s", node.Id)
	(*cmd.DefaultOptions().Registry).Register(service)

	if len(s.hcUrl) == 0 {
		return
	}

	log.Print("Starting sidecar healthchecker")
	go s.hcLoop(service, exit)
	<-exit
}
开发者ID:xiaoxiaoyijian,项目名称:micro,代码行数:29,代码来源:car.go

示例13: SaveDataIntoES

// SaveDataIntoES save metrics and events to ES by using ES client
func SaveDataIntoES(esClient *elastic.Client, indexName string, typeName string, sinkData interface{}) error {
	if indexName == "" || typeName == "" || sinkData == nil {
		return nil
	}
	// Use the IndexExists service to check if a specified index exists.
	exists, err := esClient.IndexExists(indexName).Do()
	if err != nil {
		return err
	}
	if !exists {
		// Create a new index.
		createIndex, err := esClient.CreateIndex(indexName).BodyString(mapping).Do()
		if err != nil {
			return err
		}
		if !createIndex.Acknowledged {
			return fmt.Errorf("Failed to create Index in ES cluster: %s", err)
		}
	}
	indexID := uuid.NewUUID()
	_, err = esClient.Index().
		Index(indexName).
		Type(typeName).
		Id(indexID.String()).
		BodyJson(sinkData).
		Do()
	if err != nil {
		return err
	}
	return nil
}
开发者ID:tmgardner,项目名称:heapster,代码行数:32,代码来源:elasticsearch.go

示例14: changePasswordHandler

// URL: /user_center/change_password
// 修改密码
func changePasswordHandler(handler *Handler) {
	user, _ := currentUser(handler)

	form := wtforms.NewForm(
		wtforms.NewPasswordField("current_password", "当前密码", wtforms.Required{}),
		wtforms.NewPasswordField("new_password", "新密码", wtforms.Required{}),
		wtforms.NewPasswordField("confirm_password", "新密码确认", wtforms.Required{}),
	)

	if handler.Request.Method == "POST" && form.Validate(handler.Request) {
		if form.Value("new_password") == form.Value("confirm_password") {
			if user.CheckPassword(form.Value("current_password")) {
				c := handler.DB.C(USERS)
				salt := strings.Replace(uuid.NewUUID().String(), "-", "", -1)
				c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{
					"password": encryptPassword(form.Value("new_password"), salt),
					"salt":     salt,
				}})
				message(handler, "密码修改成功", `密码修改成功`, "success")
				return
			} else {
				form.AddError("current_password", "当前密码错误")
			}
		} else {
			form.AddError("confirm_password", "密码不匹配")
		}
	}

	handler.renderTemplate("user_center/change_password.html", BASE, map[string]interface{}{
		"form":   form,
		"active": "change_password",
	})
}
开发者ID:ZuiGuangYin,项目名称:gopher,代码行数:35,代码来源:user_center.go

示例15: Create

// Create creates a workflow from the given factory name with the
// provided args.  Returns the unique UUID of the workflow. The
// workflowpb.Workflow object is saved in the topo server after
// creation.
func (m *Manager) Create(ctx context.Context, factoryName string, args []string) (string, error) {
	m.mu.Lock()
	defer m.mu.Unlock()

	// Find the factory.
	factory, ok := factories[factoryName]
	if !ok {
		return "", fmt.Errorf("no factory named %v is registered", factoryName)
	}

	// Create the initial workflowpb.Workflow object.
	w := &workflowpb.Workflow{
		Uuid:        gouuid.NewUUID().String(),
		FactoryName: factoryName,
		State:       workflowpb.WorkflowState_NotStarted,
	}

	// Let the factory parse the parameters and initialize the
	// object.
	if err := factory.Init(w, args); err != nil {
		return "", err
	}

	// Now save the workflow in the topo server.
	_, err := m.ts.CreateWorkflow(ctx, w)
	if err != nil {
		return "", err
	}

	// And we're done.
	return w.Uuid, nil
}
开发者ID:dumbunny,项目名称:vitess,代码行数:36,代码来源:manager.go


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