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

Golang bolt.Bucket类代码示例

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

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



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

示例1: putChanCommitTxns

func putChanCommitTxns(nodeChanBucket *bolt.Bucket, channel *OpenChannel) error {
	var bc bytes.Buffer
	if err := writeOutpoint(&bc, channel.ChanID); err != nil {
		return err
	}
	txnsKey := make([]byte, len(commitTxnsKey)+bc.Len())
	copy(txnsKey[:3], commitTxnsKey)
	copy(txnsKey[3:], bc.Bytes())

	var b bytes.Buffer

	if err := channel.OurCommitTx.Serialize(&b); err != nil {
		return err
	}

	if err := wire.WriteVarBytes(&b, 0, channel.OurCommitSig); err != nil {
		return err
	}

	// TODO(roasbeef): should move this into putChanFundingInfo
	scratch := make([]byte, 4)
	byteOrder.PutUint32(scratch, channel.LocalCsvDelay)
	if _, err := b.Write(scratch); err != nil {
		return err
	}
	byteOrder.PutUint32(scratch, channel.RemoteCsvDelay)
	if _, err := b.Write(scratch); err != nil {
		return err
	}

	return nodeChanBucket.Put(txnsKey, b.Bytes())
}
开发者ID:lightningnetwork,项目名称:lnd,代码行数:32,代码来源:channel.go


示例2: getGrantScopes

func getGrantScopes(bucket *bolt.Bucket, grant string) map[string]bool {
	scopesByte := bucket.Get([]byte(grant))
	if scopesByte == nil {
		return nil
	}
	return database.StringToSet(string(scopesByte))
}
开发者ID:MochiKung,项目名称:account-interface,代码行数:7,代码来源:client.go


示例3: Params

// Params returns the currently stored configuration parameters for hook h
// from bucket b.
func (GithubValidator) Params(h Hook, b *bolt.Bucket) map[string]string {
	m := make(map[string]string)
	for _, k := range []string{"secret"} {
		m[k] = string(b.Get([]byte(fmt.Sprintf("%s-%s", h.ID, k))))
	}
	return m
}
开发者ID:vampirewalk,项目名称:rehook,代码行数:9,代码来源:github_validator.go


示例4: addCityToIndex

func addCityToIndex(
	bucket *bolt.Bucket, id string, name string, locale string, population uint32,
) error {
	var err error
	var cityName *ds.CityName

	if locale == "" {
		locale = "en"
	}

	cityNameKey := []byte(ds.PrepareCityNameKey(name))
	if conflict := bucket.Get(cityNameKey); conflict != nil {
		cityName, err = ds.CityNameFromString(string(cityNameKey), string(conflict))
		if strconv.Itoa(cityName.CityId) != id {
			cityNameKey = []byte(string(cityNameKey) + "|" + id)
		}
	}

	err = bucket.Put(
		cityNameKey, []byte(
			name+"\t"+id+"\t"+locale+"\t"+strconv.Itoa(int(population)),
		),
	)

	return err
}
开发者ID:lebedev-yury,项目名称:cities-api,代码行数:26,代码来源:utils.go


示例5: fillBucket

func fillBucket(b *bolt.Bucket, prefix []byte) error {
	n := 10 + rand.Intn(50)
	for i := 0; i < n; i++ {
		v := make([]byte, 10*(1+rand.Intn(4)))
		_, err := crypto.Read(v)
		if err != nil {
			return err
		}
		k := append(prefix, []byte(fmt.Sprintf("k%d", i))...)
		if err := b.Put(k, v); err != nil {
			return err
		}
	}
	// limit depth of subbuckets
	s := 2 + rand.Intn(4)
	if len(prefix) > (2*s + 1) {
		return nil
	}
	n = 1 + rand.Intn(3)
	for i := 0; i < n; i++ {
		k := append(prefix, []byte(fmt.Sprintf("b%d", i))...)
		sb, err := b.CreateBucket(k)
		if err != nil {
			return err
		}
		if err := fillBucket(sb, append(k, '.')); err != nil {
			return err
		}
	}
	return nil
}
开发者ID:rgeronimi,项目名称:bolt,代码行数:31,代码来源:main_test.go


示例6: Params

// Params returns the currently stored configuration parameters for hook h
// from bucket b.
func (ForwardRequestAction) Params(h Hook, b *bolt.Bucket) map[string]string {
	m := make(map[string]string)
	for _, k := range []string{"url"} {
		m[k] = string(b.Get([]byte(fmt.Sprintf("%s-%s", h.ID, k))))
	}
	return m
}
开发者ID:vampirewalk,项目名称:rehook,代码行数:9,代码来源:forward_action.go


示例7: PutTokenInfo

func PutTokenInfo(tokenInfo *TokenInfo) error {
	oldTokenInfo, err := GetTokenInfo(tokenInfo.Token, tokenInfo.Client)
	if err != nil {
		return err
	}
	if oldTokenInfo != nil {
		return errors.New("duplicate token")
	}
	err = db.Update(func(tx *bolt.Tx) error {
		var clientBucket *bolt.Bucket
		clientBucket = tx.Bucket([]byte(tokenInfo.Client))
		if clientBucket == nil {
			clientBucket, err = tx.CreateBucket([]byte(tokenInfo.Client))
			if err != nil {
				return err
			}
		}
		tokenBucket, err := clientBucket.CreateBucket([]byte(tokenInfo.Token))
		if err != nil {
			return err
		}
		tokenBucket.Put([]byte("token"), []byte(tokenInfo.Token))
		tokenBucket.Put([]byte("client"), []byte(tokenInfo.Client))
		tokenBucket.Put([]byte("user"), []byte(tokenInfo.User))
		tokenBucket.Put([]byte("scopes"), []byte(tokenInfo.Scopes))
		expireBinary, err := tokenInfo.ExpireTime.MarshalBinary()
		if err != nil {
			return err
		}
		tokenBucket.Put([]byte("expire-time"), expireBinary)
		return nil
	})
	return err
}
开发者ID:MochiKung,项目名称:account-interface,代码行数:34,代码来源:access-token.go


示例8: Get

func (store *BoltStore) Get(uri string, nested bool) (interface{}, error) {
	namespace, key := util.NamespaceKey(uri)
	bucketkeys := util.PathFolders(namespace)
	var bucket *bolt.Bucket = nil
	var result interface{}
	e := store.db.View(func(tx *bolt.Tx) error {
		for _, bucketkey := range bucketkeys {
			if bucket == nil {
				bucket = tx.Bucket([]byte(bucketkey))
				if bucket == nil {
					return errors.New(uri + " not exists")
				}
			} else {
				bucket = bucket.Bucket([]byte(bucketkey))
				if bucket == nil {
					return errors.New(uri + " not exists")
				}
			}
		}
		if bucket == nil {
			return errors.New(uri + " not exists")
		}

		val, err := store.get(bucket, key, nested)
		if err != nil {
			return err
		}
		result = val
		return nil
	})
	return result, e
}
开发者ID:h2object,项目名称:h2object,代码行数:32,代码来源:store_bolt.go


示例9: Params

// Params returns the currently stored configuration parameters for hook h
// from bucket b.
func (EmailAction) Params(h Hook, b *bolt.Bucket) map[string]string {
	m := make(map[string]string)
	for _, k := range []string{"token", "domain", "address", "subject", "template"} {
		m[k] = string(b.Get([]byte(fmt.Sprintf("%s-%s", h.ID, k))))
	}
	return m
}
开发者ID:vampirewalk,项目名称:rehook,代码行数:9,代码来源:email_action.go


示例10: MultiGet

func (store *BoltStore) MultiGet(uri string, suffix string, nested bool) ([]interface{}, error) {
	results := []interface{}{}
	bucketkeys := util.PathFolders(uri)
	var bucket *bolt.Bucket = nil
	e := store.db.View(func(tx *bolt.Tx) error {
		for _, bucketkey := range bucketkeys {
			if bucket == nil {
				bucket = tx.Bucket([]byte(bucketkey))
				if bucket == nil {
					return errors.New(uri + " not exists")
				}
			} else {
				bucket = bucket.Bucket([]byte(bucketkey))
				if bucket == nil {
					return errors.New(uri + " not exists")
				}
			}
		}
		if bucket == nil {
			return errors.New(uri + " not exists")
		}

		vals, err := store.multi_get(bucket, suffix, nested)
		if err != nil {
			return err
		}
		results = append(results, vals...)
		return nil
	})
	return results, e
}
开发者ID:h2object,项目名称:h2object,代码行数:31,代码来源:store_bolt.go


示例11: Size

func (store *BoltStore) Size(uri string) (int64, error) {
	namespace, key := util.NamespaceKey(uri)
	bucketkeys := util.PathFolders(namespace)
	var bucket *bolt.Bucket = nil
	var result int64 = 0
	e := store.db.View(func(tx *bolt.Tx) error {
		for _, bucketkey := range bucketkeys {
			if bucket == nil {
				bucket = tx.Bucket([]byte(bucketkey))
				if bucket == nil {
					return errors.New(uri + " not exists")
				}
			} else {
				bucket = bucket.Bucket([]byte(bucketkey))
				if bucket == nil {
					return errors.New(uri + " not exists")
				}
			}
		}
		if bucket == nil {
			return errors.New(uri + " not exists")
		}

		result = store.size(bucket, key, nil)
		return nil
	})
	return result, e
}
开发者ID:h2object,项目名称:h2object,代码行数:28,代码来源:store_bolt.go


示例12: getData

func (this *DB) getData(bucket *bolt.Bucket) (map[string]int, ipQueue, error) {
	var addrQ ipQueue
	heapRaw := bucket.Get(boltAddrHeapKey)
	if heapRaw == nil {
		addrQ = ipQueue(make([]*ipEntry, 0, 1))
	} else {
		dec := gob.NewDecoder(bytes.NewReader(heapRaw))
		if err := dec.Decode(&addrQ); err != nil {
			return nil, nil, err
		}
	}

	var addrMap map[string]int
	mapRaw := bucket.Get(boltAddrMapKey)
	if mapRaw == nil {
		addrMap = make(map[string]int)
	} else {
		dec := gob.NewDecoder(bytes.NewReader(mapRaw))
		if err := dec.Decode(&addrMap); err != nil {
			return nil, nil, err
		}
	}

	return addrMap, addrQ, nil
}
开发者ID:mbrodala,项目名称:otto,代码行数:25,代码来源:db.go


示例13: storeWords

// Store a word,word -> word sequence
func storeWords(bucket *bolt.Bucket, word1, word2, word3 string) error {
	key := []byte(word1 + " " + word2)

	// Get value from bucket and decode it
	rawValue := bucket.Get(key)
	var value []string
	if rawValue == nil {
		value = make([]string, 0, 1)
	} else {
		if err := json.Unmarshal(rawValue, &value); err != nil {
			log.Printf("Cannot decode raw value for key '%v': %v; starting new empty key; old value is: %v", string(key), string(rawValue))
			value = make([]string, 0, 1)
		}
	}

	// Add new word to value
	value = append(value, word3)

	// Encode value and store it in bucket
	rawValue, err := json.Marshal(value)
	if err != nil {
		return err
	}

	if err := bucket.Put(key, rawValue); err != nil {
		return err
	}

	// All done
	return nil
}
开发者ID:GEPWNAGE,项目名称:Pipo,代码行数:32,代码来源:nonsentence.go


示例14: dig

func (self *TX) dig(keys [][]byte, create bool) (buckets []*bolt.Bucket, err error) {
	var bucket *bolt.Bucket
	if create {
		if bucket, err = self.tx.CreateBucketIfNotExists(keys[0]); err != nil {
			return
		}
	} else {
		if bucket = self.tx.Bucket(keys[0]); bucket == nil {
			err = ErrNotFound
			return
		}
	}
	buckets = append(buckets, bucket)
	for keys = keys[1:]; len(keys) > 0; keys = keys[1:] {
		if create {
			if bucket, err = bucket.CreateBucketIfNotExists(keys[0]); err != nil {
				return
			}
		} else {
			if bucket = bucket.Bucket(keys[0]); bucket == nil {
				err = ErrNotFound
				return
			}
		}
		buckets = append(buckets, bucket)
	}
	return
}
开发者ID:jmptrader,项目名称:unbolted,代码行数:28,代码来源:tx.go


示例15: executeSelect

func executeSelect(stmt *boltq.SelectStatement, db *bolt.DB) error {
	return db.View(func(tx *bolt.Tx) error {
		var bucket *bolt.Bucket

		for _, name := range stmt.BucketPath {
			log.Debugln("navigating to bucket", name)
			bucket = tx.Bucket([]byte(name))

			if bucket == nil {
				return fmt.Errorf("cannot find bucket %s", name)
			}
		}

		if containsAsterisk(stmt.Fields) {
			log.Debugln("interating keys")
			cursor := bucket.Cursor()

			for k, v := cursor.First(); k != nil; k, v = cursor.Next() {
				emitKeypair(k, v)
			}
		} else {
			for _, k := range stmt.Fields {
				keyBytes := []byte(k)
				v := bucket.Get(keyBytes)
				emitKeypair(keyBytes, v)
			}
		}

		return nil
	})
}
开发者ID:mnadel,项目名称:boltq,代码行数:31,代码来源:program.go


示例16: earliestChildTimestamp

// earliestChildTimestamp returns the earliest timestamp that a child node
// can have while still being valid. See section 'Timestamp Rules' in
// Consensus.md.
//
// To boost performance, earliestChildTimestamp is passed a bucket that it can
// use from inside of a boltdb transaction.
func earliestChildTimestamp(blockMap *bolt.Bucket, pb *processedBlock) types.Timestamp {
	// Get the previous MedianTimestampWindow timestamps.
	windowTimes := make(types.TimestampSlice, types.MedianTimestampWindow)
	windowTimes[0] = pb.Block.Timestamp
	parent := pb.Parent
	for i := uint64(1); i < types.MedianTimestampWindow; i++ {
		// If the genesis block is 'parent', use the genesis block timestamp
		// for all remaining times.
		if parent == (types.BlockID{}) {
			windowTimes[i] = windowTimes[i-1]
			continue
		}

		// Get the next parent's bytes. Because the ordering is specific, the
		// parent does not need to be decoded entirely to get the desired
		// information. This provides a performance boost. The id of the next
		// parent lies at the first 32 bytes, and the timestamp of the block
		// lies at bytes 40-48.
		parentBytes := blockMap.Get(parent[:])
		copy(parent[:], parentBytes[:32])
		windowTimes[i] = types.Timestamp(encoding.DecUint64(parentBytes[40:48]))
	}
	sort.Sort(windowTimes)

	// Return the median of the sorted timestamps.
	return windowTimes[len(windowTimes)/2]
}
开发者ID:kustomzone,项目名称:Sia,代码行数:33,代码来源:processedblock.go


示例17: findData

func findData(backetName string, option Option) error {
	var bucket *bolt.Bucket
	return db.View(func(tx *bolt.Tx) error {
		tx.ForEach(func(name []byte, b *bolt.Bucket) error {
			if backetName == string(name) {
				bucket = b
			}
			return nil
		})
		if bucket == nil {
			return errors.New("bucket not found")
		}
		c := bucket.Cursor()
		prefix := []byte(option.key)
		data := map[string]interface{}{}

	OUTER:
		for pk, v := c.Seek(prefix); bytes.HasPrefix(pk, prefix); pk, v = c.Next() {
			u := map[string]interface{}{}
			json.Unmarshal(v, &u)
			for fk, fv := range option.params {
				if u[fk] != fv {
					continue OUTER
				}
			}
			data[string(pk)] = u
		}

		showData(data)
		return nil
	})
}
开发者ID:willcraft,项目名称:sample-boltdb-cli,代码行数:32,代码来源:main.go


示例18: targetAdjustmentBase

// targetAdjustmentBase returns the magnitude that the target should be
// adjusted by before a clamp is applied.
func (cs *ConsensusSet) targetAdjustmentBase(blockMap *bolt.Bucket, pb *processedBlock) *big.Rat {
	// Grab the block that was generated 'TargetWindow' blocks prior to the
	// parent. If there are not 'TargetWindow' blocks yet, stop at the genesis
	// block.
	var windowSize types.BlockHeight
	parent := pb.Block.ParentID
	current := pb.Block.ID()
	for windowSize = 0; windowSize < types.TargetWindow && parent != (types.BlockID{}); windowSize++ {
		current = parent
		copy(parent[:], blockMap.Get(parent[:])[:32])
	}
	timestamp := types.Timestamp(encoding.DecUint64(blockMap.Get(current[:])[40:48]))

	// The target of a child is determined by the amount of time that has
	// passed between the generation of its immediate parent and its
	// TargetWindow'th parent. The expected amount of seconds to have passed is
	// TargetWindow*BlockFrequency. The target is adjusted in proportion to how
	// time has passed vs. the expected amount of time to have passed.
	//
	// The target is converted to a big.Rat to provide infinite precision
	// during the calculation. The big.Rat is just the int representation of a
	// target.
	timePassed := pb.Block.Timestamp - timestamp
	expectedTimePassed := types.BlockFrequency * windowSize
	return big.NewRat(int64(timePassed), int64(expectedTimePassed))
}
开发者ID:kustomzone,项目名称:Sia,代码行数:28,代码来源:processedblock.go


示例19: RepoCreateOrder

func RepoCreateOrder(order CheckoutCartPlayLoad) interface{} {
	var newOrder interface{}

	GlobalDB.Update(func(tx *bolt.Tx) error {
		orderBucket, err := tx.CreateBucketIfNotExists([]byte(OrderTable))
		if err != nil {
			HandleError(err)
			return err
		}
		var cusOrderBuck *bolt.Bucket
		if order.ChannelAccountId == nil {
			cusOrderBuck, err = orderBucket.CreateBucketIfNotExists([]byte("GUESTUSER"))
		} else {
			cusOrderBuck, err = orderBucket.CreateBucketIfNotExists([]byte(order.ChannelAccountId.(string)))
		}
		if err != nil {
			HandleError(err)
			return err
		}
		newId, _ := orderBucket.NextSequence()
		newOrder = GenerateOrder(order, newId)

		orderBytes, _ := json.Marshal(newOrder)
		cusOrderBuck.Put(TableId(newId).ToBytes(), orderBytes)

		return nil
	})

	return newOrder
}
开发者ID:compasses,项目名称:MockXServer,代码行数:30,代码来源:repo.go


示例20: Process

// Process verifies the signature and uniqueness of the random roken.
func (MailgunValidator) Process(h Hook, r Request, b *bolt.Bucket) error {
	// Check HMAC
	apikey := b.Get([]byte(fmt.Sprintf("%s-apikey", h.ID)))
	if apikey == nil {
		return errors.New("mailgun validator not initialized")
	}

	if r.Headers["Content-Type"] != "application/x-www-form-urlencoded" {
		return fmt.Errorf("unexpected Content-Type: %q", r.Headers["Content-Type"])
	}

	form, err := url.ParseQuery(string(r.Body))
	if err != nil {
		return fmt.Errorf("error parsing request body: %s", err)
	}

	timestamp := form.Get("timestamp")
	signature := []byte(form.Get("signature"))
	token := form.Get("token")

	mac := hmac.New(sha256.New, apikey)
	mac.Write([]byte(timestamp + token))
	expected := []byte(hex.EncodeToString(mac.Sum(nil)))
	if !hmac.Equal(signature, expected) {
		return errors.New("invalid signature")
	}

	// Check uniqueness
	tokens := b.Bucket([]byte("tokens"))
	if p := tokens.Get([]byte(token)); p != nil {
		return errors.New("duplicate request token received")
	}
	return tokens.Put([]byte(token), []byte{})
}
开发者ID:vampirewalk,项目名称:rehook,代码行数:35,代码来源:mailgun_validator.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang bolt.BucketStats类代码示例发布时间:2022-05-24
下一篇:
Golang bolt.Open函数代码示例发布时间: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