Skip to content

Instantly share code, notes, and snippets.

@icub3d
Created August 8, 2013 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icub3d/6180350 to your computer and use it in GitHub Desktop.
Save icub3d/6180350 to your computer and use it in GitHub Desktop.
An example of using GridFS in MongoDB.
package main
import (
"bufio"
"fmt"
"io"
"labix.org/v2/mgo"
"os"
"path"
"strings"
)
func main() {
// Initialize the mongodb connection.
session, err := mgo.Dial("localhost")
if err != nil {
fmt.Printf("initializing session:", err)
return
}
defer session.Close()
// Get our GridFS collection.
gfs := session.DB("test").GridFS("")
scanner := bufio.NewScanner(os.Stdin)
quit := false
for !quit {
fmt.Print("gfs> ")
if !scanner.Scan() {
break
}
line := scanner.Text()
parts := strings.Split(line, " ")
cmd := parts[0]
args := parts[1:]
switch cmd {
// List and find are the same. They only differ in the filter.
case "put":
file, err := os.Open(args[0])
if err != nil {
fmt.Println("opening file:", err)
continue
}
gfile, err := gfs.Create(path.Base(args[0]))
if err != nil {
fmt.Println("creating grid file:", err)
file.Close()
continue
}
io.Copy(gfile, file)
file.Close()
gfile.Close()
case "get":
gfile, err := gfs.Open(args[0])
if err != nil {
fmt.Println("getting file:", err)
continue
}
io.Copy(os.Stdout, gfile)
gfile.Close()
case "quit":
quit = true
default:
fmt.Println("unrecognized command:", cmd, args)
}
}
if err := scanner.Err(); err != nil {
fmt.Println("reading stdin:", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment