golang和boltdb:使用闭包包装存储桶ForEach函数

In my code I use alot of repeating code to iterate over nested buckets in a bolddb database. I would like to do some refactoring, wrapping these repeating codes into new functions.

I know I need to use closures for this, but the extra db.View layer gives me headaches.

More precisely, I would like to wrap the bucket.ForEach function into a new function. This function creates a view transaction of the database, selects the nested bucket and returns a new function that lets me iterate over the given bucket.

The code signature of the newly created code would be something like this:

ForEachBucket(bucket_name string, *bolt.DB) func() {}

The code that I want to wrap:

func ForEachBucket(bucketname string, db *bolt.DB)  {

    db.View(func(tx *bolt.Tx) error {
        rootBkt := tx.Bucket([]byte("rootbucket")) // always the same
        interestingBkt := rootBkt.Bucket([]byte(bucketname))
        if nestedBkt := interestingBkt.Bucket([]byte("underlying")); nestedBkt != nil {
            mapBkt.ForEach(func(k, v []byte) error {
                // do something here
                    }
            })
            return nil
        })
}

I want to create a new function (using closures) that wraps the above code and returns a foreach like function.

I didn't actually catch what you want, but I'll try to answer.

You may have an callback argument that you pass to ForEach

    func ForEachBucket(db *bolt.DB, bucketname string, f func(b *bolt.Bucket) error {
        // ...
        return mapBucket.ForEach(f) // do not forget about returned error here
    }

More general: https://play.golang.org/p/LQlZHOWZTfi