Skip to content

Instantly share code, notes, and snippets.

@jasontconnell
Created December 12, 2014 19:34
Show Gist options
  • Save jasontconnell/901444088ffb3dd97613 to your computer and use it in GitHub Desktop.
Save jasontconnell/901444088ffb3dd97613 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"encoding/json"
"os"
)
var configFile string = "config.json"
type Configuration struct {
Url, Database string
}
var config Configuration = Configuration{}
type Post struct {
Id string `bson="_id"`
Body string `bson="body"`
Title string `bson:"title"`
Tags []string `bson:"tags"`
Date time.Time `bson:"date"`
}
type Repository struct {
databaseName string
url string
session *mgo.Session
}
func (repo *Repository) Initialize(url, dbname string) {
repo.url = url
repo.databaseName = dbname
repo.session, _ = mgo.Dial(repo.url)
}
func (repo *Repository) OpenCollection(collection string) *mgo.Collection {
return repo.session.DB(repo.databaseName).C(collection)
}
func (repo *Repository) Close() {
repo.session.Close()
}
type PostRepository struct {
Repository
collection string
}
func NewPostRepository(config Configuration) *PostRepository {
postRepo := new(PostRepository)
postRepo.Initialize(config.Url, config.Database)
postRepo.collection = "posts"
return postRepo
}
func (postRepo PostRepository) GetPost(tag string) *Post {
post := &Post { Id: "1", Body: "Body", Title: "Title", Tags: make([]string,5), Date: time.Now() };
return post
}
func (postRepo PostRepository) GetPosts(tag string) []Post {
posts := postRepo.OpenCollection(postRepo.collection)
postArray := []Post{}
posts.Find(bson.M{ "tags": tag }).All(&postArray)
return postArray
}
func init(){
file, err := os.Open(configFile)
if err != nil {
fmt.Println("Error opening json file ", err, configFile)
}
decoder := json.NewDecoder(file)
err2 := decoder.Decode(&config)
if err2 != nil {
fmt.Println("error decoding json file", err);
}
}
func main() {
postRepo := NewPostRepository(config)
defer postRepo.Close()
posts := postRepo.GetPosts("mongodb")
fmt.Printf("got %d\n", len(posts))
for _, post := range posts {
fmt.Println(post.Title)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment