本文整理匯總了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
}
示例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
}
示例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 ¬ice
}
示例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
}
示例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
}
示例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
}
示例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)
}
}
示例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
}
}
示例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
}
示例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.")
}
示例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)
}
}
}
示例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
})
}
示例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
}
示例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
}
示例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
}