當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。