示例#1
0
文件: server.go 项目: rdterner/todos
func NewServer(bxPath string) *Server {
	// Open a buckets database.
	bx, err := buckets.Open(bxPath)
	if err != nil {
		log.Fatalf("couldn't open buckets db %q: %v", bxPath, err)
	}

	// Create/open bucket for storing todos.
	bucket, err := bx.New([]byte("todos"))
	if err != nil {
		log.Fatalf("couldn't create/open todos bucket: %v", err)
	}

	// Initialize our controller for handling specific routes.
	control := NewController(bucket)

	// Create and setup our router.
	mux := httprouter.New()
	mux.POST("/day/:day", control.post)
	mux.GET("/day/:day", control.getDayTasks)
	mux.GET("/weekend", control.getWeekendTasks)
	mux.GET("/weekdays", control.getWeekdayTasks)

	// Start our web server.
	srv := httptest.NewServer(mux)
	return &Server{srv.URL, bx, srv}
}
示例#2
0
// Show we can insert items into a bucket and get them back out.
func ExampleBucket_Insert() {
	bx, _ := buckets.Open(tempfile())
	defer os.Remove(bx.Path())
	defer bx.Close()

	letters, _ := bx.New([]byte("letters"))

	// Setup items to insert in `letters` bucket.
	items := []struct {
		Key, Value []byte
	}{
		{[]byte("A"), []byte("alpha")},
		{[]byte("B"), []byte("beta")},
		{[]byte("C"), []byte("gamma")},
	}

	// Insert items into `letters` bucket.
	if err := letters.Insert(items); err != nil {
		fmt.Println("could not insert items!")
	}

	// Get items back out in separate read-only transaction.
	results, _ := letters.Items()

	for _, item := range results {
		fmt.Printf("%s -> %s\n", item.Key, item.Value)
	}

	// Output:
	// A -> alpha
	// B -> beta
	// C -> gamma
}
示例#3
0
// Show that we can apply a function to the k/v pairs
// of keys within a given range.
func ExampleBucket_MapRange() {
	bx, _ := buckets.Open(tempfile())
	defer os.Remove(bx.Path())
	defer bx.Close()

	// Delete any existing bucket named "years".
	bx.Delete([]byte("years"))

	// Create a new bucket named "years".
	years, _ := bx.New([]byte("years"))

	// Setup items to insert in `years` bucket
	items := []struct {
		Key, Value []byte
	}{
		{[]byte("1970"), []byte("70")},
		{[]byte("1975"), []byte("75")},
		{[]byte("1980"), []byte("80")},
		{[]byte("1985"), []byte("85")},
		{[]byte("1990"), []byte("90")}, // min = 1990
		{[]byte("1995"), []byte("95")}, // min < 1995 < max
		{[]byte("2000"), []byte("00")}, // max = 2000
		{[]byte("2005"), []byte("05")},
		{[]byte("2010"), []byte("10")},
	}

	// Insert 'em.
	if err := years.Insert(items); err != nil {
		fmt.Printf("could not insert items in `years` bucket: %v\n", err)
	}

	// Time range to map over: 1990 <= key <= 2000.
	min := []byte("1990")
	max := []byte("2000")

	// Setup slice of items to collect results.
	type item struct {
		Key, Value []byte
	}
	results := []item{}

	// Anon func to map over matched keys.
	do := func(k, v []byte) error {
		results = append(results, item{k, v})
		return nil
	}

	if err := years.MapRange(do, min, max); err != nil {
		fmt.Printf("could not map items within range: %v\n", err)
	}

	for _, item := range results {
		fmt.Printf("%s -> %s\n", item.Key, item.Value)
	}
	// Output:
	// 1990 -> 90
	// 1995 -> 95
	// 2000 -> 00
}
示例#4
0
// Ensure we can open/close a buckets db.
func TestOpen(t *testing.T) {
	bx, err := buckets.Open(tempfile())
	if err != nil {
		t.Error(err.Error())
	}
	defer os.Remove(bx.Path())
	defer bx.Close()
}
示例#5
0
// Show that we can apply a function to the k/v pairs
// of keys with a given prefix.
func ExampleBucket_MapPrefix() {
	bx, _ := buckets.Open(tempfile())
	defer os.Remove(bx.Path())
	defer bx.Close()

	// Create a new things bucket.
	things, _ := bx.New([]byte("things"))

	// Setup items to insert.
	items := []struct {
		Key, Value []byte
	}{
		{[]byte("A"), []byte("1")},   // `A` prefix match
		{[]byte("AA"), []byte("2")},  // match
		{[]byte("AAA"), []byte("3")}, // match
		{[]byte("AAB"), []byte("2")}, // match
		{[]byte("B"), []byte("O")},
		{[]byte("BA"), []byte("0")},
		{[]byte("BAA"), []byte("0")},
	}

	// Insert 'em.
	if err := things.Insert(items); err != nil {
		fmt.Printf("could not insert items in `things` bucket: %v\n", err)
	}

	// Now collect each item whose key starts with "A".
	prefix := []byte("A")

	// Setup slice of items.
	type item struct {
		Key, Value []byte
	}
	results := []item{}

	// Anon func to map over matched keys.
	do := func(k, v []byte) error {
		results = append(results, item{k, v})
		return nil
	}

	if err := things.MapPrefix(do, prefix); err != nil {
		fmt.Printf("could not map items with prefix %s: %v\n", prefix, err)
	}

	for _, item := range results {
		fmt.Printf("%s -> %s\n", item.Key, item.Value)
	}
	// Output:
	// A -> 1
	// AA -> 2
	// AAA -> 3
	// AAB -> 2
}
示例#6
0
func ExampleBucket() {
	// Open the database.
	bx, _ := buckets.Open(tempfile())
	defer os.Remove(bx.Path())
	defer bx.Close()

	// Create a hits bucket
	hits, _ := bx.New([]byte("hits"))

	// Start our web server
	count := counter{hits}
	srv := httptest.NewServer(count)
	defer srv.Close()

	// Get every path multiple times.
	paths := []string{
		"/foo",
		"/bar",
		"/baz",
		"/quux",
		"/thud",
		"/xyzzy",
	}
	for id := 0; id < 10; id++ {
		if err := client(id, srv.URL, paths); err != nil {
			fmt.Printf("client error: %v", err)
		}
	}

	// Check the final result
	do := func(k, v []byte) error {
		fmt.Printf("hits to %s: %d\n", k, decode(v))
		return nil
	}
	hits.Map(do)
	// outputs ...
	// hits to /bar: 10
	// hits to /baz: 10
	// hits to /foo: 10
	// hits to /quux: 10
	// hits to /thud: 10
	// hits to /xyzzy: 10

	// Output:
	// hits to /bar: 10
	// hits to /baz: 10
	// hits to /foo: 10
	// hits to /quux: 10
	// hits to /thud: 10
	// hits to /xyzzy: 10
}
示例#7
0
func NewBoltDBStore() *BoltDBStore {
	boltDbStore := BoltDBStore{}

	if db, err := buckets.Open("fourty_four.db"); err != nil {
		l4g.Critical("Not db connection")
		panic(err)
	} else {
		boltDbStore.db = db
		boltDbStore.user = NewBoltDbUserStore(&boltDbStore)
		boltDbStore.channel = NewBoltDbChannelStore(&boltDbStore)
		boltDbStore.post = NewBoltDbPostStore(&boltDbStore)
	}
	return &boltDbStore
}
示例#8
0
文件: xhub.go 项目: rwilliams04/xhub
// NewServer creates a new studies server instance.
func NewServer(addr, dbpath string) *Server {
	// Open a buckets database.
	bux, err := buckets.Open(dbpath)
	if err != nil {
		log.Fatalf("couldn't open buckets db %q: %v\n", dbpath, err)
	}

	// Initialize our controller for handling specific routes.
	control := NewController(addr, bux)

	// Create and setup our router.
	mux := httprouter.New()

	// Setup study handlers.
	mux.POST("/studies", control.Study.Post)
	mux.GET("/studies", control.Study.List)
	mux.GET("/studies/:study", control.Study.Get)
	mux.DELETE("/studies/:study", control.Study.Delete)

	// Setup trial handlers.
	mux.POST("/studies/:study/trials", control.Trial.Post)
	mux.GET("/studies/:study/trials", control.Trial.List)
	mux.GET("/studies/:study/trials/:trial", control.Trial.Get)
	mux.DELETE("/studies/:study/trials/:trial", control.Trial.Delete)

	// Setup study-level file handlers.
	mux.POST("/studies/:study/files", control.File.Post)
	mux.GET("/studies/:study/files", control.File.List)
	mux.GET("/studies/:study/files/:file", control.File.Get)
	mux.DELETE("/studies/:study/files/:file", control.File.Delete)

	// Setup trial-level file handlers.
	mux.POST("/files/:study/:trial", control.File.Post)
	mux.GET("/files/:study/:trial", control.File.List)
	mux.GET("/files/:study/:trial/:file", control.File.Get)
	mux.DELETE("/files/:study/:trial/:file", control.File.Delete)

	// Setup index/make/view/edit handlers.
	// mux.GET("/view/studies", control.Study.Index)
	// mux.GET("/make/studies", control.Study.Make)
	mux.POST("/save/studies", control.Study.Save)
	mux.GET("/view/studies/:study", control.Study.View)
	mux.GET("/edit/studies/:study", control.Study.Edit)

	return &Server{addr, mux, bux}
}
示例#9
0
// Show that we get items for keys within a given range.
func ExampleBucket_RangeItems() {
	bx, _ := buckets.Open(tempfile())
	defer os.Remove(bx.Path())
	defer bx.Close()

	// Create a new bucket named "years".
	years, _ := bx.New([]byte("years"))

	// Setup items to insert in `years` bucket
	items := []struct {
		Key, Value []byte
	}{
		{[]byte("1970"), []byte("70")},
		{[]byte("1975"), []byte("75")},
		{[]byte("1980"), []byte("80")},
		{[]byte("1985"), []byte("85")},
		{[]byte("1990"), []byte("90")}, // min = 1990
		{[]byte("1995"), []byte("95")}, // min < 1995 < max
		{[]byte("2000"), []byte("00")}, // max = 2000
		{[]byte("2005"), []byte("05")},
		{[]byte("2010"), []byte("10")},
	}

	// Insert 'em.
	if err := years.Insert(items); err != nil {
		fmt.Printf("could not insert items in `years` bucket: %v\n", err)
	}

	// Time range: 1990 <= key <= 2000.
	min := []byte("1990")
	max := []byte("2000")

	results, err := years.RangeItems(min, max)
	if err != nil {
		fmt.Printf("could not get items within range: %v\n", err)
	}

	for _, item := range results {
		fmt.Printf("%s -> %s\n", item.Key, item.Value)
	}
	// Output:
	// 1990 -> 90
	// 1995 -> 95
	// 2000 -> 00
}
示例#10
0
// Show that we can get items for all keys with a given prefix.
func ExampleBucket_PrefixItems() {
	bx, _ := buckets.Open(tempfile())
	defer os.Remove(bx.Path())
	defer bx.Close()

	// Create a new things bucket.
	things, _ := bx.New([]byte("things"))

	// Setup items to insert.
	items := []struct {
		Key, Value []byte
	}{
		{[]byte("A"), []byte("1")},   // `A` prefix match
		{[]byte("AA"), []byte("2")},  // match
		{[]byte("AAA"), []byte("3")}, // match
		{[]byte("AAB"), []byte("2")}, // match
		{[]byte("B"), []byte("O")},
		{[]byte("BA"), []byte("0")},
		{[]byte("BAA"), []byte("0")},
	}

	// Insert 'em.
	if err := things.Insert(items); err != nil {
		fmt.Printf("could not insert items in `things` bucket: %v\n", err)
	}

	// Now get items whose key starts with "A".
	prefix := []byte("A")

	results, err := things.PrefixItems(prefix)
	if err != nil {
		fmt.Printf("could not get items with prefix %q: %v\n", prefix, err)
	}

	for _, item := range results {
		fmt.Printf("%s -> %s\n", item.Key, item.Value)
	}
	// Output:
	// A -> 1
	// AA -> 2
	// AAA -> 3
	// AAB -> 2
}
示例#11
0
// Show we can put an item in a bucket and get it back out.
func ExampleBucket_Put() {
	bx, _ := buckets.Open(tempfile())
	defer os.Remove(bx.Path())
	defer bx.Close()

	// Create a new `things` bucket.
	bucket := []byte("things")
	things, _ := bx.New(bucket)

	// Put key/value into the `things` bucket.
	key, value := []byte("A"), []byte("alpha")
	if err := things.Put(key, value); err != nil {
		fmt.Printf("could not insert item: %v", err)
	}

	// Read value back in a different read-only transaction.
	got, _ := things.Get(key)

	fmt.Printf("The value of %q in `%s` is %q\n", key, bucket, got)

	// Output:
	// The value of "A" in `things` is "alpha"
}
示例#12
0
文件: prefix.go 项目: arvenil/buckets
func main() {
	// Open a buckets database.
	bx, err := buckets.Open(tempFilePath())
	if err != nil {
		log.Fatalf("couldn't open db: %v", err)
	}

	// Delete and close the db when done.
	defer os.Remove(bx.Path())
	defer bx.Close()

	// Create a bucket for storing todos.
	bucket, err := bx.New([]byte("todos"))
	if err != nil {
		log.Fatalf("couldn't create todos bucket: %v", err)
	}

	// Initialize our controller for handling specific routes.
	control := NewController(bucket)

	// Create and setup our router.
	router := httprouter.New()
	router.GET("/:day", control.get)
	router.POST("/:day", control.post)

	// Start our web server.
	srv := httptest.NewServer(router)
	defer srv.Close()

	// Daily todos for client to post.
	posts := []*Todo{
		&Todo{Day: "mon", Task: "milk cows"},
		&Todo{Day: "mon", Task: "feed cows"},
		&Todo{Day: "mon", Task: "wash cows"},
		&Todo{Day: "tue", Task: "wash laundry"},
		&Todo{Day: "tue", Task: "fold laundry"},
		&Todo{Day: "tue", Task: "iron laundry"},
		&Todo{Day: "wed", Task: "flip burgers"},
		&Todo{Day: "thu", Task: "join army"},
		&Todo{Day: "fri", Task: "kill time"},
		&Todo{Day: "sat", Task: "have beer"},
		&Todo{Day: "sat", Task: "make merry"},
		&Todo{Day: "sun", Task: "take aspirin"},
		&Todo{Day: "sun", Task: "pray quietly"},
	}

	// Create our client.
	client := new(Client)

	// Have our client post each daily todo.
	for _, todo := range posts {
		url := srv.URL + "/" + todo.Day
		if err := client.post(url, todo); err != nil {
			fmt.Printf("client post error: %v", err)
		}
	}

	// Have our client get a list of tasks for each day.
	week := []string{"mon", "tue", "wed", "thu", "fri", "sat", "sun"}
	for _, day := range week {
		url := srv.URL + "/" + day
		tasks, err := client.get(url)
		if err != nil {
			fmt.Printf("client get error: %v", err)
		}
		fmt.Printf("%s: %s\n", day, tasks)
	}

	// Output:
	// mon: milk cows, feed cows, wash cows
	// tue: wash laundry, fold laundry, iron laundry
	// wed: flip burgers
	// thu: join army
	// fri: kill time
	// sat: have beer, make merry
	// sun: take aspirin, pray quietly
}
示例#13
0
func main() {
	// Open a buckets database.
	bx, err := buckets.Open(tempFilePath())
	if err != nil {
		log.Fatalf("couldn't open db: %v", err)
	}

	// Delete and close the db when done.
	defer os.Remove(bx.Path())
	defer bx.Close()

	// Create a bucket for storing todos.
	bucket, err := bx.New([]byte("todos"))
	if err != nil {
		log.Fatalf("couldn't create todos bucket: %v", err)
	}

	// Create our service for handling routes.
	service := NewService(bucket)

	// Create and setup our router.
	router := mux.New()
	router.GET("/:day", service.get)
	router.POST("/:day", service.post)

	// Start our web server.
	srv := httptest.NewServer(router)
	defer srv.Close()

	// Daily todos for client to post.
	posts := map[string]*Todo{
		"/mon": &Todo{Day: "mon", Task: "milk cows"},
		"/tue": &Todo{Day: "tue", Task: "fold laundry"},
		"/wed": &Todo{Day: "wed", Task: "flip burgers"},
		"/thu": &Todo{Day: "thu", Task: "join army"},
		"/fri": &Todo{Day: "fri", Task: "kill time"},
		"/sat": &Todo{Day: "sat", Task: "make merry"},
		"/sun": &Todo{Day: "sun", Task: "pray quietly"},
	}

	// Create our client.
	client := new(Client)

	for path, todo := range posts {
		url := srv.URL + path
		if err := client.post(url, todo); err != nil {
			fmt.Printf("client post error: %v", err)
		}
	}

	for path, _ := range posts {
		url := srv.URL + path
		task, err := client.get(url)
		if err != nil {
			fmt.Printf("client get error: %v", err)
		}
		fmt.Printf("%s: %s\n", path, task)
	}

	// Output:
	// /mon: milk cows
	// /tue: fold laundry
	// /wed: flip burgers
	// /thu: join army
	// /fri: kill time
	// /sat: make merry
	// /sun: pray quietly
}
示例#14
0
文件: post.go 项目: joyrexus/buckets
func main() {
	// Open a buckets database.
	bx, err := buckets.Open(tempFilePath())
	if err != nil {
		log.Fatalf("couldn't open db: %v", err)
	}

	// Delete and close the db when done.
	defer os.Remove(bx.Path())
	defer bx.Close()

	// Create a bucket for storing todos.
	todos, err := bx.New([]byte("todos"))
	if err != nil {
		log.Fatalf("couldn't create todos bucket: %v", err)
	}

	// Start our web server.
	handler := service{todos}
	srv := httptest.NewServer(handler)
	defer srv.Close()

	// Daily todos to post.
	posts := map[string]*Todo{
		"/mon": {Day: "mon", Task: "milk cows"},
		"/tue": {Day: "tue", Task: "fold laundry"},
		"/wed": {Day: "wed", Task: "flip burgers"},
		"/thu": {Day: "thu", Task: "join army"},
		"/fri": {Day: "fri", Task: "kill time"},
		"/sat": {Day: "sat", Task: "make merry"},
		"/sun": {Day: "sun", Task: "pray quietly"},
	}

	// Make a series of post requests to our server.
	for path, todo := range posts {
		url := srv.URL + path
		bodyType := "application/json"
		body, err := todo.Encode()
		if err != nil {
			log.Print(err)
		}
		resp, err := http.Post(url, bodyType, body)
		if err != nil {
			log.Print(err)
		}
		if verbose {
			log.Printf("client: %s\n", resp.Status)
		}
	}

	// Test that each encoded todo sent to the server was
	// in fact stored in the todos bucket.
	for route, want := range posts {
		// Get encoded todo sent to route.
		encoded, err := todos.Get([]byte(route))
		if err != nil {
			log.Fatalf("todo bucket is missing entry for %s: %v", route, err)
		}
		got, err := decode(encoded)
		if err != nil {
			log.Fatalf("could not decode entry for %s: %v", route, err)
		}
		if got.Task != want.Task {
			log.Fatalf("%s: got %v, want %v", route, got.Task, want.Task)
		}
		if !reflect.DeepEqual(got, want) {
			log.Fatalf("%s: got %v, want %v", route, got, want)
		}
	}

	// Show the encoded todos now stored in the todos bucket.
	do := func(k, v []byte) error {
		todo, err := decode(v)
		if err != nil {
			log.Print(err)
		}
		fmt.Printf("%s: %s\n", k, todo.Task)
		return nil
	}
	todos.Map(do)

	// Output:
	// /fri: kill time
	// /mon: milk cows
	// /sat: make merry
	// /sun: pray quietly
	// /thu: join army
	// /tue: fold laundry
	// /wed: flip burgers
}