本文整理汇总了Golang中github.com/pborman/uuid.NewUUID函数的典型用法代码示例。如果您正苦于以下问题:Golang NewUUID函数的具体用法?Golang NewUUID怎么用?Golang NewUUID使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewUUID函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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 := ®istry.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 := ®istry.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 := ®istry.Node{
Id: id,
Address: host,
Port: port,
}
service := ®istry.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
示例16: frameworkRegistered
// ---------------------- Handlers for Events from Master --------------- //
func (driver *MesosSchedulerDriver) frameworkRegistered(from *upid.UPID, pbMsg proto.Message) {
log.V(2).Infoln("Handling scheduler driver framework registered event.")
msg := pbMsg.(*mesos.FrameworkRegisteredMessage)
masterInfo := msg.GetMasterInfo()
masterPid := masterInfo.GetPid()
frameworkId := msg.GetFrameworkId()
if driver.status == mesos.Status_DRIVER_ABORTED {
log.Infof("ignoring FrameworkRegisteredMessage from master %s, driver is aborted", masterPid)
return
}
if driver.connected {
log.Infoln("ignoring FrameworkRegisteredMessage from master, driver is already connected", masterPid)
return
}
if driver.stopped() {
log.Infof("ignoring FrameworkRegisteredMessage from master %s, driver is stopped", masterPid)
return
}
if !driver.masterPid.Equal(from) {
log.Warningf("ignoring framework registered message because it was sent from '%v' instead of leading master '%v'", from, driver.masterPid)
return
}
log.Infof("Framework registered with ID=%s\n", frameworkId.GetValue())
driver.frameworkInfo.Id = frameworkId // generated by master.
driver.connected = true
driver.failover = false
driver.connection = uuid.NewUUID()
driver.withScheduler(func(s Scheduler) { s.Registered(driver, frameworkId, masterInfo) })
}
开发者ID:basho-labs,项目名称:mesos-go,代码行数:36,代码来源:scheduler.go
示例17: run
func (s *Sidecar) run() {
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 := ®istry.Node{
Id: id,
Address: host,
Port: port,
}
service := ®istry.Service{
Name: s.name,
Nodes: []*registry.Node{node},
}
log.Infof("Registering %s", node.Id)
(*cmd.DefaultOptions().Registry).Register(service)
if len(s.hcUrl) > 0 {
log.Info("Starting sidecar healthchecker")
exitCh := make(chan bool, 1)
go s.hcLoop(service, exitCh)
defer func() {
exitCh <- true
}()
}
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
<-ch
}
开发者ID:yonglehou,项目名称:micro,代码行数:33,代码来源:car.go
示例18: Sub
func Sub(types []string) (chan *event.Record, chan bool) {
mtx.Lock()
defer mtx.Unlock()
exit := make(chan bool)
bus := &sub{
id: uuid.NewUUID().String(),
ch: make(chan *event.Record, bufferSize),
}
// global subscribe
if len(types) == 0 {
subs[all] = append(subs[all], bus)
}
// type subscribe
for _, typ := range types {
subs[typ] = append(subs[typ], bus)
}
go func() {
<-exit
// we've been unsubscribed
mtx.Lock()
// remove the global subscriber
if len(types) == 0 {
var subscribers []*sub
for _, s := range subs[all] {
if s.id == bus.id {
continue
}
subscribers = append(subscribers, s)
}
subs[all] = subscribers
}
// remove subscribers for type
for _, typ := range types {
var subscribers []*sub
for _, s := range subs[typ] {
if s.id == bus.id {
continue
}
subscribers = append(subscribers, s)
}
subs[typ] = subscribers
}
mtx.Unlock()
}()
return bus.ch, exit
}
开发者ID:micro,项目名称:event-srv,代码行数:59,代码来源:event.go
示例19: Provision
func (provisioner *quobyteVolumeProvisioner) Provision() (*api.PersistentVolume, error) {
if provisioner.options.PVC.Spec.Selector != nil {
return nil, fmt.Errorf("claim Selector is not supported")
}
provisioner.config = "BASE"
provisioner.tenant = "DEFAULT"
cfg, err := parseAPIConfig(provisioner.plugin, provisioner.options.Parameters)
if err != nil {
return nil, err
}
for k, v := range provisioner.options.Parameters {
switch goStrings.ToLower(k) {
case "registry":
provisioner.registry = v
case "user":
provisioner.user = v
case "group":
provisioner.group = v
case "quobytetenant":
provisioner.tenant = v
case "quobyteconfig":
provisioner.config = v
case "adminsecretname",
"adminsecretnamespace",
"quobyteapiserver":
continue
default:
return nil, fmt.Errorf("invalid option %q for volume plugin %s", k, provisioner.plugin.GetPluginName())
}
}
if !validateRegistry(provisioner.registry) {
return nil, fmt.Errorf("Quoybte registry missing or malformed: must be a host:port pair or multiple pairs separated by commas")
}
// create random image name
provisioner.volume = fmt.Sprintf("kubernetes-dynamic-pvc-%s", uuid.NewUUID())
manager := &quobyteVolumeManager{
config: cfg,
}
vol, sizeGB, err := manager.createVolume(provisioner)
if err != nil {
return nil, err
}
pv := new(api.PersistentVolume)
pv.Spec.PersistentVolumeSource.Quobyte = vol
pv.Spec.PersistentVolumeReclaimPolicy = provisioner.options.PersistentVolumeReclaimPolicy
pv.Spec.AccessModes = provisioner.options.PVC.Spec.AccessModes
if len(pv.Spec.AccessModes) == 0 {
pv.Spec.AccessModes = provisioner.plugin.GetAccessModes()
}
pv.Spec.Capacity = api.ResourceList{
api.ResourceName(api.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGB)),
}
return pv, nil
}
开发者ID:maisem,项目名称:kubernetes,代码行数:59,代码来源:quobyte.go
示例20: forgotPasswordHandler
// URL: /forgot_password
// 忘记密码,输入用户名和邮箱,如果匹配,发出邮件
func forgotPasswordHandler(handler *Handler) {
form := wtforms.NewForm(
wtforms.NewTextField("username", "用户名", "", wtforms.Required{}),
wtforms.NewTextField("email", "电子邮件", "", wtforms.Email{}),
)
if handler.Request.Method == "POST" {
if form.Validate(handler.Request) {
var user User
c := handler.DB.C(USERS)
err := c.Find(bson.M{"username": form.Value("username")}).One(&user)
if err != nil {
form.AddError("username", "没有该用户")
} else if user.Email != form.Value("email") {
form.AddError("username", "用户名和邮件不匹配")
} else {
message2 := `Hi %s,<br>
我们的系统收到一个请求,说你希望通过电子邮件重新设置你在 Golang中国 的密码。你可以点击下面的链接开始重设密码:
<a href="%s/reset/%s">%s/reset/%s</a><br>
如果这个请求不是由你发起的,那没问题,你不用担心,你可以安全地忽略这封邮件。
如果你有任何疑问,可以回复<a href="mailto:[email protected]">[email protected]</a>向我提问。`
code := strings.Replace(uuid.NewUUID().String(), "-", "", -1)
c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"resetcode": code}})
message2 = fmt.Sprintf(message2, user.Username, Config.Host, code, Config.Host, code)
if Config.SendMailPath == "" {
webhelpers.SendMail(
"[Golang中国]重设密码",
message2,
Config.FromEmail,
[]string{user.Email},
webhelpers.SmtpConfig{
Username: Config.SmtpUsername,
Password: Config.SmtpPassword,
Host: Config.SmtpHost,
Addr: Config.SmtpAddr,
},
true,
)
} else {
webhelpers.SendMailExec(
"[Golang中国]重设密码",
message2,
Config.FromEmail,
[]string{user.Email},
Config.SendMailPath,
true,
)
}
message(handler, "通过电子邮件重设密码", "一封包含了重设密码指令的邮件已经发送到你的注册邮箱,按照邮件中的提示,即可重设你的密码。", "success")
return
}
}
}
handler.renderTemplate("account/forgot_password.html", BASE, map[string]interface{}{"form": form})
}
开发者ID:zhaoshiling1017,项目名称:gopher,代码行数:61,代码来源:account.go
注:本文中的github.com/pborman/uuid.NewUUID函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论