func getTestDB() *bolt.DB { database, err := bolt.Open(getDBPath(), 0600, &bolt.Options{Timeout: 1 * time.Second}) if err != nil { log.Fatal(err) } db.GenerateDefaultBucket(db.GetBucketName(), database) return database }
// Update a feature flag func PutFeature(tx *bolt.Tx, feature m.FeatureFlag) error { features := tx.Bucket([]byte(db.GetBucketName())) bytes, err := json.Marshal(feature) if err != nil { return err } err = features.Put([]byte(feature.Key), bytes) if err != nil { return err } return nil }
// Get a feature flag thanks to its key func GetFeature(tx *bolt.Tx, featureKey string) (m.FeatureFlag, error) { features := tx.Bucket([]byte(db.GetBucketName())) bytes := features.Get([]byte(featureKey)) if bytes == nil { return m.FeatureFlag{}, fmt.Errorf("Unable to find feature") } feature := m.FeatureFlag{} err := json.Unmarshal(bytes, &feature) if err != nil { return m.FeatureFlag{}, err } return feature, nil }
// Get a list of feature flags func GetFeatures(tx *bolt.Tx) (m.FeatureFlags, error) { featuresBucket := tx.Bucket([]byte(db.GetBucketName())) cursor := featuresBucket.Cursor() features := make(m.FeatureFlags, 0) for key, value := cursor.First(); key != nil; key, value = cursor.Next() { feature := m.FeatureFlag{} err := json.Unmarshal(value, &feature) if err != nil { return nil, err } features = append(features, feature) } return features, nil }
func main() { address := flag.String("a", ":8080", "address to listen") boltLocation := flag.String("d", "bolt.db", "location of the database file") flag.Parse() // Open the DB connection database, err := bolt.Open(*boltLocation, 0600, &bolt.Options{Timeout: 1 * time.Second}) if err != nil { log.Fatal(err) } // Close the DB connection on exit defer database.Close() // Generate the default bucket db.GenerateDefaultBucket(db.GetBucketName(), database) api := h.APIHandler{FeatureService: s.FeatureService{DB: database}} // Create and listen for the HTTP server router := h.NewRouter(api) log.Fatal(http.ListenAndServe(*address, router)) }
// Delete a feature flag thanks to its key func RemoveFeature(tx *bolt.Tx, featureKey string) error { features := tx.Bucket([]byte(db.GetBucketName())) return features.Delete([]byte(featureKey)) }
// Tell if a feature exists func FeatureExists(tx *bolt.Tx, featureKey string) bool { features := tx.Bucket([]byte(db.GetBucketName())) bytes := features.Get([]byte(featureKey)) return bytes != nil }