• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang dynamodbattribute.ConvertToMap函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: PutItem

// PutItem puts an item on the table.
func (t *Table) PutItem(v interface{}, opts ...option.PutItemInput) error {
	req := &dynamodb.PutItemInput{
		TableName: t.Name,
	}

	var itemMapped map[string]*dynamodb.AttributeValue
	var err error
	if marshaller, ok := v.(item.Marshaler); ok {
		itemMapped, err = marshaller.MarshalItem()
	} else {
		itemMapped, err = dynamodbattribute.ConvertToMap(v)
	}
	if err != nil {
		return err
	}

	req.Item = itemMapped

	for _, f := range opts {
		f(req)
	}

	_, err = t.DynamoDB.PutItem(req)
	return err
}
开发者ID:nabeken,项目名称:aws-go-dynamodb,代码行数:26,代码来源:table.go


示例2: main

func main() {
	svc := dynamodb.New(session.New(), &aws.Config{Region: aws.String("eu-central-1")})

	k := Key{
		Email: "[email protected]",
	}

	item, err := dynamodbattribute.ConvertToMap(k)
	if err != nil {
		panic(err)
	}

	result, err := svc.GetItem(&dynamodb.GetItemInput{
		TableName: aws.String("Users"),
		Key:       item,
	})
	if err != nil {
		panic(err)
	}

	r := Record{}
	err = dynamodbattribute.ConvertFromMap(result.Item, &r)

	fmt.Println(r)
}
开发者ID:proydakov,项目名称:aws-sdk-go-example,代码行数:25,代码来源:dynamodb_get_item.go


示例3: PrimaryKey

func (i *TestItem) PrimaryKey() map[string]*dynamodb.AttributeValue {
	primaryKey := i.PrimaryKeyMap()

	item, _ := dynamodbattribute.ConvertToMap(primaryKey)

	return item
}
开发者ID:nabeken,项目名称:aws-go-dynamodb,代码行数:7,代码来源:table_test.go


示例4: Record

// Record marshals the job result into a dynamodb.AttributeValue struct, and writes
// the result item to DyanmoDB.
func (r *ResultRecorder) Record(result *wordfreq.JobResult) error {
	// Construct a result item representing what data we want to write to DynamoDB.
	recordItem := resultRecord{
		Filename: path.Join(result.Job.Bucket, result.Job.Key),
		Words:    map[string]int{},
	}
	for _, w := range result.Words {
		recordItem.Words[w.Word] = w.Count
	}

	// Use the ConvertToX helpers to marshal a Go struct to a dyanmodb.AttributeValue
	// type. This greatly simplifies the code needed to create the attribute
	// value item.
	av, err := dynamodbattribute.ConvertToMap(recordItem)
	if err != nil {
		return fmt.Errorf("unable to serialize result to dyanmoDB.AttributeValue, %v", err)
	}
	_, err = r.svc.PutItem(&dynamodb.PutItemInput{
		TableName: aws.String(r.tableName),
		Item:      av,
	})
	if err != nil {
		return fmt.Errorf("unable to record result, %v", err)
	}

	return nil
}
开发者ID:Tsingson1988,项目名称:aws-go-wordfreq-sample,代码行数:29,代码来源:result_recorder.go


示例5: BenchmarkPutItem

func BenchmarkPutItem(b *testing.B) {
	cfg := aws.Config{
		DisableSSL:  aws.Bool(true),
		Credentials: credentials.NewStaticCredentials("AKID", "SECRET", ""),
	}
	server := successRespServer([]byte(`{}`))
	cfg.Endpoint = aws.String(server.URL)

	svc := dynamodb.New(&cfg)
	svc.Handlers.Send.Clear()
	svc.Handlers.Send.PushBack(func(r *service.Request) {
		r.HTTPResponse = &http.Response{
			StatusCode: http.StatusOK,
			Status:     http.StatusText(http.StatusOK),
			Body:       noopBody,
		}
	})

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		av, err := dynamodbattribute.ConvertToMap(dbItem{Key: "MyKey", Data: "MyData"})
		if err != nil {
			b.Fatal("benchPutItem, expect no ConvertToMap errors", err)
		}
		params := &dynamodb.PutItemInput{
			Item:      av,
			TableName: aws.String("tablename"),
		}
		_, err = svc.PutItem(params)
		if err != nil {
			b.Error("benchPutItem, expect no request errors", err)
		}
	}
}
开发者ID:ahamilton55,项目名称:aws-sdk-go,代码行数:34,代码来源:dynamodb_test.go


示例6: benchPutItemParallel

func benchPutItemParallel(p, c int, b *testing.B) {
	svc := dynamodb.New(&aws.Config{
		DisableSSL: aws.Bool(true),
	})

	av, err := dynamodbattribute.ConvertToMap(dbItem{Key: "MyKey", Data: "MyData"})
	if err != nil {
		b.Fatal("expect no ConvertToMap errors", err)
	}
	params := &dynamodb.PutItemInput{
		Item:      av,
		TableName: aws.String(testTableName),
	}
	b.N = c

	b.ResetTimer()
	b.SetParallelism(p)
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			_, err = svc.PutItem(params)
			if err != nil {
				b.Error("expect no request errors", err)
			}
		}
	})
}
开发者ID:jloper3,项目名称:amazon-ecs-cli,代码行数:26,代码来源:dynamodb_live_test.go


示例7: output

// output expects key value data to print to stdout
func (out stdout) output(data record) error {
	item, err := dynamodbattribute.ConvertToMap(data.Data)
	if err != nil {
		return err
	}
	fmt.Println(item)
	return nil
}
开发者ID:chamal-sapumohotti,项目名称:aws-sdk-go,代码行数:9,代码来源:logging.go


示例8: main

func main() {
	//testTableDelete()
	//chack table status

	//testTableCreate()
	//chack table status
	//if creating,wait for active

	svc := dynamodb.New(&aws.Config{Region: aws.String("ap-northeast-1")})
	/*
		scanParams := &dynamodb.ScanInput{
			TableName:aws.String("access_log_range"),
			AttributesToGet:[]*string{
				aws.String("id"),
				aws.String("time"),
				aws.String("body_bytes_sent"),
				aws.String("bytes_sent"),
				aws.String("forwardedfor"),
				aws.String("query_string"),
				aws.String("referer"),
				aws.String("remote_addr"),
				aws.String("request_length"),
				aws.String("request_method"),
				aws.String("request_time"),
				aws.String("request_uri"),
				aws.String("status"),
				aws.String("tag"),
				aws.String("useragent"),
			},
			//Limit: aws.Int64(1000000),
		}
	*/

	r := Record{
		Key:       "key127.0.0.1",
		RemoteID:  "abc-001",
		OtherData: map[string]int{"a": 1, "b": 2, "c": 3},
		Timestamp: time.Now().UTC().Unix(),
	}
	item, err := dynamodbattribute.ConvertToMap(r)
	log.Println(item)

	result, err := svc.PutItem(&dynamodb.PutItemInput{
		Item:      item,
		TableName: aws.String("result"),
	})

	fmt.Println(result, err)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}
	fmt.Println(result)

}
开发者ID:oranie,项目名称:dynamodb-sample,代码行数:58,代码来源:main.go


示例9: Register

// Register the service in the registry
func (c *Client) Register(name string, endpoint string) (*Service, error) {

	// Check whether the registry has been previously created. If not create before registration.
	if exists, err := c.Registry.Exists(); err != nil {
		return nil, err
	} else if !exists {
		if err := c.Registry.Create(); err != nil {
			return nil, err
		}
	}

	// Create Service
	service := &Service{Name: name, Endpoint: endpoint, stopHeartbeat: make(chan bool)}

	// Heartbeat function - updates expiry
	heartbeat := func() {
		// Update service Expiry based on TTL and current time
		service.Expiry = time.Now().Unix() + ServiceTTL

		// Update service entry in registry
		if av, err := dynamodbattribute.ConvertToMap(*service); err != nil {
			return
		} else {
			_, err := c.svc.PutItem(&dynamodb.PutItemInput{
				Item:      av,
				TableName: c.config.GetRegistryName(),
			})

			if err != nil {
				return
			}
		}
	}

	// Ensure call heartbeat at least once
	heartbeat()

	// Start goroutine to send heartbeat
	go func() {
		for {
			select {
			case <-service.stopHeartbeat:
				return
			default:
				// Pause for interval
				time.Sleep(HeartbeatInterval)

				// Call heartbeat function
				heartbeat()
			}
		}
	}()

	return service, nil
}
开发者ID:ibmendoza,项目名称:roster,代码行数:56,代码来源:client.go


示例10: tryToLock

// tryToLock tries to create a new item in DynamoDB
// every `DynamoDBLockRetryInterval`. As long as the item
// cannot be created (because it already exists), it will
// be retried. If the operation fails due to an error, it
// is sent to the errors channel.
// When the lock could be acquired successfully, the success
// channel is closed.
func (l *DynamoDBLock) tryToLock(stop, success chan struct{}, errors chan error) {
	ticker := time.NewTicker(DynamoDBLockRetryInterval)

	record := DynamoDBRecord{
		Path:  recordPathForVaultKey(l.key),
		Key:   recordKeyForVaultKey(l.key),
		Value: []byte(l.value),
	}
	item, err := dynamodbattribute.ConvertToMap(record)
	if err != nil {
		errors <- err
		return
	}

	for {
		select {
		case <-stop:
			ticker.Stop()
		case <-ticker.C:
			_, err := l.backend.client.PutItem(&dynamodb.PutItemInput{
				TableName:           aws.String(l.backend.table),
				Item:                item,
				ConditionExpression: aws.String("attribute_not_exists(#p) or attribute_not_exists(#k)"),
				ExpressionAttributeNames: map[string]*string{
					"#p": aws.String("Path"),
					"#k": aws.String("Key"),
				},
			})
			if err != nil {
				if err, ok := err.(awserr.Error); ok && err.Code() != "ConditionalCheckFailedException" {
					errors <- err
				}
				if l.recovery {
					_, err := l.backend.client.DeleteItem(&dynamodb.DeleteItemInput{
						TableName: aws.String(l.backend.table),
						Key: map[string]*dynamodb.AttributeValue{
							"Path": {S: aws.String(record.Path)},
							"Key":  {S: aws.String(record.Key)},
						},
					})
					if err != nil {
						errors <- fmt.Errorf("could not delete lock record: %s", err)
					} else {
						l.recovery = false
					}
				}
			} else {
				ticker.Stop()
				close(success)
			}
		}
	}
}
开发者ID:geckoboard,项目名称:vault,代码行数:60,代码来源:dynamodb.go


示例11: putResource

func putResource(svc *dynamodb.DynamoDB, resource Resource, tableName string) error {
	item, err := dynamodbattribute.ConvertToMap(resource)
	if err != nil {
		return err
	}
	_, err = svc.PutItem(&dynamodb.PutItemInput{
		Item:      item,
		TableName: aws.String(tableName),
	})
	return err

}
开发者ID:porcup,项目名称:ngproxy,代码行数:12,代码来源:dynamodb.go


示例12: getDynamodbPutItemParams

func getDynamodbPutItemParams(b *testing.B) *dynamodb.PutItemInput {
	av, err := dynamodbattribute.ConvertToMap(struct {
		Key  string
		Data string
	}{Key: "MyKey", Data: "MyData"})
	if err != nil {
		b.Fatal("benchPutItem, expect no ConvertToMap errors", err)
	}
	return &dynamodb.PutItemInput{
		Item:      av,
		TableName: aws.String("tablename"),
	}
}
开发者ID:rlister,项目名称:ecr-login,代码行数:13,代码来源:build_bench_test.go


示例13: Put

// Put is used to insert or update an entry
func (d *DynamoDBBackend) Put(entry *Entry) error {
	defer metrics.MeasureSince([]string{"dynamodb", "put"}, time.Now())

	record := DynamoDBRecord{
		Path:  recordPathForVaultKey(entry.Key),
		Key:   recordKeyForVaultKey(entry.Key),
		Value: entry.Value,
	}
	item, err := dynamodbattribute.ConvertToMap(record)
	if err != nil {
		return fmt.Errorf("could not convert prefix record to DynamoDB item: %s", err)
	}
	requests := []*dynamodb.WriteRequest{{
		PutRequest: &dynamodb.PutRequest{
			Item: item,
		},
	}}

	for _, prefix := range prefixes(entry.Key) {
		record = DynamoDBRecord{
			Path: recordPathForVaultKey(prefix),
			Key:  fmt.Sprintf("%s/", recordKeyForVaultKey(prefix)),
		}
		item, err := dynamodbattribute.ConvertToMap(record)
		if err != nil {
			return fmt.Errorf("could not convert prefix record to DynamoDB item: %s", err)
		}
		requests = append(requests, &dynamodb.WriteRequest{
			PutRequest: &dynamodb.PutRequest{
				Item: item,
			},
		})
	}

	return d.batchWriteRequests(requests)
}
开发者ID:geckoboard,项目名称:vault,代码行数:37,代码来源:dynamodb.go


示例14: MarshalItem

// MarshalItem implements ItemMarshaler interface.
func (i TestItem) MarshalItem() (map[string]*dynamodb.AttributeValue, error) {
	if i.IsStartKey() {
		item := i.PrimaryKey()
		return item, nil
	}

	itemMapped, err := dynamodbattribute.ConvertToMap(i)
	if err != nil {
		return nil, err
	}
	if i.Password != "" {
		itemMapped["password"] = attributes.String(hashedPassword(i.Password))
	}

	return itemMapped, nil
}
开发者ID:nabeken,项目名称:aws-go-dynamodb,代码行数:17,代码来源:table_test.go


示例15: Discover

// Query the registry for named service
func (c *Client) Discover(name string) (*Service, error) {

	// Make sure registry is active
	if active, _ := c.Registry.IsActive(); active == true {
		expressionAttributeValues := map[string]interface{}{
			":NameVal":   name,
			":ExpiryVal": time.Now().Unix(),
		}

		ean := map[string]*string{
			"#N": aws.String("Name"),
		}

		eav, err := dynamodbattribute.ConvertToMap(expressionAttributeValues)
		if err != nil {
			return nil, err
		}

		resp, err := c.svc.Query(&dynamodb.QueryInput{
			TableName:                 c.config.GetRegistryName(),
			KeyConditionExpression:    aws.String("#N = :NameVal"),
			FilterExpression:          aws.String("Expiry > :ExpiryVal"),
			ExpressionAttributeValues: eav,
			ExpressionAttributeNames:  ean,
		})

		if err != nil {
			return nil, err
		}

		if len(resp.Items) > 0 {
			// Randomly select one of the available endpoints (in effect load balancing between available endpoints)
			service := Service{}
			err = dynamodbattribute.ConvertFromMap(resp.Items[rand.Intn(len(resp.Items))], &service)
			if err != nil {
				return nil, err
			}
			return &service, nil
		} else {
			// No service found
			return nil, ErrServiceNotFound
		}
	} else {
		return nil, ErrRegistryNotActive
	}
}
开发者ID:ibmendoza,项目名称:roster,代码行数:47,代码来源:client.go


示例16: main

func main() {

	svc := dynamodb.New(session.New(), &aws.Config{Endpoint: aws.String("http://localhost:8000"), Region: aws.String("us-east-1")})

	//var data map[string]interface{}

	file, e := ioutil.ReadFile("./mockdata/MOCK_DATA-gym.json")
	//fmt.Print(string(file))
	if e != nil {
		fmt.Printf("File error: %v\n", e)
		os.Exit(1)
	}

	var u []Gym
	json.Unmarshal(file, &u)

	for i := 0; i < len(u); i++ {
		fmt.Printf(" Name: %v\n", u[i].Name)

		item, err := dynamodbattribute.ConvertToMap(u[i])
		if err != nil {
			fmt.Println("Failed to convert", err)
			return
		}
		fmt.Printf("Item %v\n", item)

		//fmt.Printf("Data %v\n", data[user])
		params := &dynamodb.PutItemInput{
			Item:      item,
			TableName: aws.String("gym"),
		}
		resp, err := svc.PutItem(params)

		if err != nil {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
			return
		}
		// Pretty-print the response data.
		fmt.Println(resp)

	}
	//fmt.Printf("AL: Data %v", data)
}
开发者ID:softwaremisconduct,项目名称:local-dynamodb,代码行数:45,代码来源:gym-populate.go


示例17: main

func main() {

	svc := dynamodb.New(session.New(), &aws.Config{Endpoint: aws.String("http://localhost:8000"), Region: aws.String("us-east-1")})

	file, e := ioutil.ReadFile("./mockdata/MOCK_DATA-user-2.json")
	if e != nil {
		fmt.Printf("File error: %v\n", e)
		os.Exit(1)
	}

	var u []User
	json.Unmarshal(file, &u)

	for i := 0; i < len(u); i++ {
		fmt.Printf(" First Name: %v\n", u[i].FirstName)

		encPass, cryptErr := Crypt([]byte(u[i].Password))
		if cryptErr != nil {
			fmt.Println("Failed to hash password", cryptErr)
			return
		}
		u[i].EncPassword = string(encPass)
		u[i].Password = ""

		item, err := dynamodbattribute.ConvertToMap(u[i])
		if err != nil {
			fmt.Println("Failed to convert", err)
			return
		}
		fmt.Printf("Item %v\n", item)

		params := &dynamodb.PutItemInput{
			Item:      item,
			TableName: aws.String("user"),
		}
		resp, err := svc.PutItem(params)

		if err != nil {
			fmt.Println(err.Error())
			return
		}
		fmt.Println(resp)

	}
}
开发者ID:softwaremisconduct,项目名称:local-dynamodb,代码行数:45,代码来源:user-populate.go


示例18: PutItem

// PutItem puts an item on the table.
func (t *Table) PutItem(item interface{}, opts ...option.PutItemInput) error {
	req := &dynamodb.PutItemInput{
		TableName: t.Name,
	}

	itemMapped, err := dynamodbattribute.ConvertToMap(item)
	if err != nil {
		return err
	}

	req.Item = itemMapped

	for _, f := range opts {
		f(req)
	}

	_, err = t.DynamoDB.PutItem(req)
	return err
}
开发者ID:tabe1hands,项目名称:aws-go-dynamodb,代码行数:20,代码来源:table.go


示例19: ExclusiveStartKey

// ExclusiveStartKey sets an ExclusiveStartKey in dynamodb.QueryInput.
func ExclusiveStartKey(v interface{}) QueryInput {
	return func(req *dynamodb.QueryInput) error {
		var err error
		var esk map[string]*dynamodb.AttributeValue

		if key, ok := v.(map[string]*dynamodb.AttributeValue); ok {
			esk = key
		} else if marshaller, ok := v.(item.Marshaler); ok {
			esk, err = marshaller.MarshalItem()
		} else {
			esk, err = dynamodbattribute.ConvertToMap(v)
		}

		if err != nil {
			return err
		}

		req.ExclusiveStartKey = esk
		return nil
	}
}
开发者ID:nabeken,项目名称:aws-go-dynamodb,代码行数:22,代码来源:query.go


示例20: main

func main() {
	svc := dynamodb.New(session.New(), &aws.Config{Region: aws.String("eu-central-1")})

	r := Record{
		Email:           "[email protected]",
		CheckEmailToken: "29jd9j2dm3932jdhewk4",
	}

	item, err := dynamodbattribute.ConvertToMap(r)
	if err != nil {
		panic(err)
	}
	result, err := svc.PutItem(&dynamodb.PutItemInput{
		TableName: aws.String("Users"),
		Item:      item,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(result)
}
开发者ID:proydakov,项目名称:aws-sdk-go-example,代码行数:21,代码来源:dynamodb_put_item.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang dynamodbstreams.New函数代码示例发布时间:2022-05-24
下一篇:
Golang dynamodb.DynamoDB类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap