Created
August 8, 2013 00:33
-
-
Save icub3d/6180350 to your computer and use it in GitHub Desktop.
An example of using GridFS in MongoDB.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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