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


Golang uuid.NewRandom函数代码示例

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


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

示例1: getSessionSecrets

func getSessionSecrets(filename string) ([]string, error) {
	// Build secrets list
	secrets := []string{}

	if len(filename) != 0 {
		sessionSecrets, err := latest.ReadSessionSecrets(filename)
		if err != nil {
			return nil, fmt.Errorf("error reading sessionSecretsFile %s: %v", filename, err)
		}

		if len(sessionSecrets.Secrets) == 0 {
			return nil, fmt.Errorf("sessionSecretsFile %s contained no secrets", filename)
		}

		for _, s := range sessionSecrets.Secrets {
			secrets = append(secrets, s.Authentication)
			secrets = append(secrets, s.Encryption)
		}
	} else {
		// Generate random signing and encryption secrets if none are specified in config
		secrets = append(secrets, fmt.Sprintf("%x", md5.Sum([]byte(uuid.NewRandom().String()))))
		secrets = append(secrets, fmt.Sprintf("%x", md5.Sum([]byte(uuid.NewRandom().String()))))
	}

	return secrets, nil
}
开发者ID:pombredanne,项目名称:atomic-enterprise,代码行数:26,代码来源:auth_config.go

示例2: DecodeClientData

// DecodeClientData attempts to decode the data received from the client. Gob is tried first followed
// by JSON then XML. Once the data is decoded, the resulting Wrapper is placed on the client receive
// channel.
func DecodeClientData(c *data.Client) error {
	var wrap data.Wrapper
	rdr := bytes.NewReader(c.DataIn)

	// Attempt decoding from Gob first
	err := gob.NewDecoder(rdr).Decode(&wrap)
	if err != nil {
		rdr.Seek(0, 0)
		// Attempt JSON next
		err := json.NewDecoder(rdr).Decode(&wrap)
		if err != nil {
			rdr.Seek(0, 0)
			switch err.(type) {
			case *json.SyntaxError:
				// JSON decoding failed, try XML
				err := xml.NewDecoder(rdr).Decode(&wrap)
				if err != nil {
					return err
				}
			default:
				return err
			}
		}
	}

	// If the message doesn't have an id, generate one.
	if wrap.Message.Uuid == "" {
		wrap.Message.Uuid = uuid.NewRandom().String()
	}

	c.Receive <- &wrap
	return nil
}
开发者ID:JonPulfer,项目名称:gomq,代码行数:36,代码来源:server.go

示例3: newNotice

func newNotice(config *Configuration, err Error, extra ...interface{}) *Notice {
	notice := Notice{
		APIKey:       config.APIKey,
		Error:        err,
		Token:        uuid.NewRandom().String(),
		ErrorMessage: err.Message,
		ErrorClass:   err.Class,
		Env:          config.Env,
		Hostname:     config.Hostname,
		Backtrace:    composeStack(err.Stack, config.Root),
		ProjectRoot:  config.Root,
		Context:      Context{},
	}

	for _, thing := range extra {
		switch t := thing.(type) {
		case Context:
			notice.setContext(t)
		case Params:
			notice.Params = t
		case CGIData:
			notice.CGIData = t
		case url.URL:
			notice.URL = t.String()
		}
	}

	return &notice
}
开发者ID:emmetog,项目名称:conveyor,代码行数:29,代码来源:notice.go

示例4: makeFixedMessage

func makeFixedMessage(encoder client.Encoder, size uint64) [][]byte {
	ma := make([][]byte, 1)
	hostname, _ := os.Hostname()
	pid := int32(os.Getpid())

	msg := &message.Message{}
	msg.SetType("hekabench")
	msg.SetTimestamp(time.Now().UnixNano())
	msg.SetUuid(uuid.NewRandom())
	msg.SetSeverity(int32(6))
	msg.SetEnvVersion("0.8")
	msg.SetPid(pid)
	msg.SetHostname(hostname)
	rdm := &randomDataMaker{
		src: rand.NewSource(time.Now().UnixNano()),
	}
	buf := make([]byte, size)
	payloadSuffix := bytes.NewBuffer(buf)
	_, err := io.CopyN(payloadSuffix, rdm, int64(size))
	payload := fmt.Sprintf("hekabench: %s", hostname)
	if err == nil {
		payload = fmt.Sprintf("%s - %s", payload, payloadSuffix.String())
	} else {
		log.Println("Error getting random string: ", err)
	}
	msg.SetPayload(payload)
	var stream []byte
	if err := encoder.EncodeMessageStream(msg, &stream); err != nil {
		log.Println(err)
	}
	ma[0] = stream
	return ma
}
开发者ID:hellcoderz,项目名称:heka,代码行数:33,代码来源:main.go

示例5: Random

// Random creates a random ID (uses uuid.NewRandom() which uses crypto.Random()
// under the covers)
func Random() ID {
	id, err := Read(uuid.NewRandom())
	if err != nil {
		panic(fmt.Sprintf("Unable to generate random peer id: %s", err))
	}
	return id
}
开发者ID:shizhh,项目名称:lantern,代码行数:9,代码来源:buuid.go

示例6: getTestMessage

func getTestMessage() *message.Message {
	hostname, _ := os.Hostname()
	field, _ := message.NewField("foo", "bar", message.Field_RAW)
	msg := &message.Message{}
	msg.SetType("TEST")
	msg.SetTimestamp(5123456789)
	msg.SetPid(9283)
	msg.SetUuid(uuid.NewRandom())
	msg.SetLogger("GoSpec")
	msg.SetSeverity(int32(6))
	msg.SetEnvVersion("0.8")
	msg.SetPid(int32(os.Getpid()))
	msg.SetHostname(hostname)
	msg.AddField(field)

	data := []byte("data")
	field1, _ := message.NewField("bytes", data, message.Field_RAW)
	field2, _ := message.NewField("int", int64(999), message.Field_RAW)
	field2.AddValue(int64(1024))
	field3, _ := message.NewField("double", float64(99.9), message.Field_RAW)
	field4, _ := message.NewField("bool", true, message.Field_RAW)
	field5, _ := message.NewField("foo", "alternate", message.Field_RAW)
	msg.AddField(field1)
	msg.AddField(field2)
	msg.AddField(field3)
	msg.AddField(field4)
	msg.AddField(field5)
	return msg
}
开发者ID:honkfestival,项目名称:heka,代码行数:29,代码来源:lua_sandbox_test.go

示例7: DeliverRecord

func (sr *sRunner) DeliverRecord(record []byte, del Deliverer) {
	unframed := record
	pack := <-sr.ir.InChan()
	if sr.unframer != nil {
		unframed = sr.unframer.UnframeRecord(record, pack)
		if unframed == nil {
			pack.Recycle()
			return
		}
	}
	if sr.useMsgBytes {
		// Put the blob in the pack and let the decoder sort it out.
		messageLen := len(unframed)
		if messageLen > cap(pack.MsgBytes) {
			pack.MsgBytes = make([]byte, messageLen)
		}
		pack.MsgBytes = pack.MsgBytes[:messageLen]
		copy(pack.MsgBytes, unframed)
	} else {
		// Put the record data in the payload.
		pack.Message.SetUuid(uuid.NewRandom())
		pack.Message.SetTimestamp(time.Now().UnixNano())
		pack.Message.SetLogger(sr.ir.Name())
		pack.Message.SetPayload(string(unframed))
	}
	// Give the input one last chance to mutate the pack.
	if sr.packDecorator != nil {
		sr.packDecorator(pack)
	}
	if del == nil {
		sr.ir.Deliver(pack)
	} else {
		del.Deliver(pack)
	}
}
开发者ID:orangemi,项目名称:heka,代码行数:35,代码来源:splitter_runner.go

示例8: Call

func (c *Client) Call(method string, args ...interface{}) (interface{}, error) {
	message := &Request{
		ID:     uuid.NewRandom().String(),
		Method: method,
		Args:   args,
	}
	c.messages <- message

	// put our listener on the queue and listen for it
	c.lock.Lock()
	results := make(chan *Response, 1)
	c.waiting[message.ID] = results
	c.lock.Unlock()

	select {
	case result := <-results:
		var err error
		if result.Error != "" {
			err = errors.New(result.Error)
		}
		return result.Payload, err

	case <-c.context.Done():
		return nil, ErrStopped
	}
}
开发者ID:asteris-llc,项目名称:jack,代码行数:26,代码来源:client.go

示例9: CreateMessage

func CreateMessage(userId string, receiverId string, mr types.MessageRequest) error {
	var err error
	err = nil

	if err = utilsservice.CheckIfMatchExists(userId, receiverId); err == nil {
		var m types.Message

		m.SenderId = uuid.Parse(userId)
		m.ReceiverId = uuid.Parse(receiverId)
		m.MessageId = uuid.NewRandom()
		m.IsRead = false
		m.Text = strings.Replace(mr.Text, "'", "''", -1)
		if mr.Timestamp != 0 {
			m.Timestamp = int64(time.Unix(mr.Timestamp, 0).UTC().Unix())
		} else {
			m.Timestamp = int64(time.Now().UTC().Unix())
		}

		if err = messageRepo.CreateMessage(m); err == nil {
			err = chatservice.UpdateLastMessageChat(userId, receiverId, m.Text)

			if lastActivity, errA := activityservice.GetUserActivity(receiverId); errA == nil {
				senderUsername, _ := utilsservice.GetUserUsername(userId)
				pushMessage := fmt.Sprintf("%s: %s", senderUsername, m.Text)
				notificationsservice.SendPushNotification(lastActivity.DeviceType, lastActivity.PushToken, pushMessage)
			}
		}
	}

	return err
}
开发者ID:somanole,项目名称:gaitapi,代码行数:31,代码来源:MessageService.go

示例10: cli

func cli(cn int, wg *sync.WaitGroup) {
	defer wg.Done()
	//time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
	conn, err := net.Dial("tcp", "127.0.0.1:1314")
	if err != nil {
		fmt.Println("Error!")
		return
	}
	defer conn.Close()
	clientConn := new(ClientConn)
	clientConn.Client = kamaji.NewClient(conn)
	clientConn.ID = uuid.NewRandom()
	clientConn.Name = clientConn.ID.String()
	clientConn.Name = fmt.Sprintf("node%03d.test.now", cn)
	clientConn.sender = make(chan *proto_msg.KamajiMessage)
	go clientConn.messageSender()
	//go reportStats(clientConn)
	for {
		tmp, err := clientConn.ReadMessage()
		if err != nil {
			break
		}
		message := &proto_msg.KamajiMessage{}
		err = proto.Unmarshal(tmp, message)
		if err != nil {
			fmt.Println(err)
			break
		}
		handleMessage(clientConn, message)
	}
	fmt.Println("Exiting Client Loop.")
}
开发者ID:smaragden,项目名称:kamaji,代码行数:32,代码来源:node.go

示例11: Run

func (w *Worker) Run() error {
	uid := uuid.NewRandom()
	copy(w.Id[:], uid)

	w.lastjob = time.Now()
	w.FileCache = map[string][]byte{}

	wd, err := os.Getwd()
	if err != nil {
		return err
	}
	os.Setenv("PATH", os.Getenv("PATH")+":"+wd)

	if w.Wait == 0 {
		w.Wait = 10 * time.Second
	}

	for {
		wait, err := w.dojob()
		if err != nil {
			log.Print(err)
		}
		if w.MaxIdle > 0 && time.Now().Sub(w.lastjob) > w.MaxIdle {
			log.Printf("no jobs received for %v, shutting down", w.MaxIdle)
			return nil
		}
		if wait {
			<-time.After(w.Wait)
		}
	}
}
开发者ID:rwcarlsen,项目名称:cloudlus,代码行数:31,代码来源:worker.go

示例12: serveDocumentsCreate

func serveDocumentsCreate(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
	serveAPI(res, req, func() interface{} {
		ctx := appengine.NewContext(req)
		session, _ := sessionStore.Get(req, "session")

		email, ok := session.Values["email"].(string)
		if !ok {
			return HTTPError{403, "access denied"}
		}

		var document Document
		err := json.NewDecoder(req.Body).Decode(&document)
		if err != nil {
			return err
		}
		if document.ID != "" {
			return fmt.Errorf("invalid document: id must not be set")
		}
		document.ID = uuid.NewRandom().String()
		userKey := datastore.NewKey(ctx, "User", email, 0, nil)
		docKey := datastore.NewKey(ctx, "Document", document.ID, 0, userKey)
		docKey, err = datastore.Put(ctx, docKey, &document)
		if err != nil {
			return err
		}
		return document
	})
}
开发者ID:nischalkarki,项目名称:tutorials,代码行数:28,代码来源:api.go

示例13: payloadParser

// Standard text log file parser
func payloadParser(fm *FileMonitor, isRotated bool) (bytesRead int64, err error) {
	var (
		n      int
		pack   *PipelinePack
		record []byte
	)
	for err == nil {
		n, record, err = fm.parser.Parse(fm.fd)
		if err != nil {
			if err == io.EOF && isRotated {
				record = fm.parser.GetRemainingData()
			} else if err == io.ErrShortBuffer {
				fm.ir.LogError(fmt.Errorf("record exceeded MAX_RECORD_SIZE %d", message.MAX_RECORD_SIZE))
				err = nil // non-fatal, keep going
			}
		}
		if len(record) > 0 {
			payload := string(record)
			pack = <-fm.ir.InChan()
			pack.Message.SetUuid(uuid.NewRandom())
			pack.Message.SetTimestamp(time.Now().UnixNano())
			pack.Message.SetType("logfile")
			pack.Message.SetHostname(fm.hostname)
			pack.Message.SetLogger(fm.logger_ident)
			pack.Message.SetPayload(payload)
			fm.outChan <- pack
			fm.last_logline_start = fm.seek + bytesRead
			fm.last_logline = payload
		}
		bytesRead += int64(n)
	}
	return
}
开发者ID:Jimdo,项目名称:heka,代码行数:34,代码来源:logfile_input.go

示例14: buildPodManifest

func (img *Image) buildPodManifest(exec []string) *schema.PodManifest {
	bpm := schema.BlankPodManifest()

	// Figure out working path that doesn't exist in the image's rootfs
	workDir := ".jetpack.build."
	for {
		if _, err := os.Stat(img.getRootfs().Path(workDir)); err != nil {
			if os.IsNotExist(err) {
				break
			}
			panic(err)
		}
		workDir = fmt.Sprintf(".jetpack.build.%v", uuid.NewRandom())
	}

	bprta := img.RuntimeApp()
	bprta.Name.Set("jetpack/build")
	bprta.App = &types.App{
		Exec:             exec,
		WorkingDirectory: "/" + workDir,
		User:             "0",
		Group:            "0",
	}
	bpm.Apps = append(bpm.Apps, bprta)

	// This is needed by freebsd-update at least, should be okay to
	// allow this in builders.
	bpm.Annotations.Set("jetpack/jail.conf/allow.chflags", "true")
	bpm.Annotations.Set("jetpack/jail.conf/securelevel", "0")

	return bpm
}
开发者ID:sdoumbouya,项目名称:jetpack,代码行数:32,代码来源:build.go

示例15: setup

func (j *Job) setup() error {
	var err error
	if j.wd == "" {
		j.wd, err = os.Getwd()
		if err != nil {
			return err
		}
	}
	j.dir = uuid.NewRandom().String()
	err = os.MkdirAll(j.dir, 0755)
	if err != nil {
		return err
	}

	if err := os.Chdir(j.dir); err != nil {
		return err
	}

	for _, f := range j.Infiles {
		err := ioutil.WriteFile(f.Name, f.Data, 0755)
		if err != nil {
			return err
		}
	}
	return nil
}
开发者ID:rwcarlsen,项目名称:cloudlus,代码行数:26,代码来源:job.go


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