[ GoLang ] mongodb mgo

http://qiita.com/rubytomato@github/items/4192e2340d81c0c39ca5

  1. Install Go

download tar, extract, and set the path

sudo tar -C /usr/local -xzf go1.8.3.linux-amd64.tar.gz

put this in .bashrc

export PATH=$PATH:/usr/local/go/bin

go that comes from ubuntu golang-go package is quite old ( version 1.8.2 ).

`​go get` will comes with go version at least 1.8.3 ( ref ), so it is recommended to install from tar.

2. hello.go

package main

import "fmt"

func main() {
 fmt.Printf("hello, world\n")
}

compile

go build hello.go

run

./hello

run without compile

go run hello.go

3. Install Mgo

go get gopkg.in/mgo.v2

Trobleshooting

$ go get gopkg.in/mgo.v2
# gopkg.in/mgo.v2
../../go/src/gopkg.in/mgo.v2/auth.go:38: import /home/pong/go/pkg/linux_amd64/gopkg.in/mgo.v2/internal/scram.a: not a package file

solution

remove $HOME/go/pkg

ref : https://groups.google.com/forum/#!topic/golang-nuts/VGa3vprcNiE

 

hello_mgo.go

package main

import (
        "fmt"
	"log"
        "gopkg.in/mgo.v2"
        "gopkg.in/mgo.v2/bson"
)

type Person struct {
        Name string
        Phone string
}

func main() {
        session, err := mgo.Dial("localhost") // server1.example.com,server2.example.com
        if err != nil {
                panic(err)
        }
        defer session.Close()

        // Optional. Switch the session to a monotonic behavior.
        session.SetMode(mgo.Monotonic, true)

        c := session.DB("test").C("people")
        err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
	               &Person{"Cla", "+55 53 8402 8510"})
        if err != nil {
                log.Fatal(err)
        }

        result := Person{}
        err = c.Find(bson.M{"name": "Ale"}).One(&result)
        if err != nil {
                log.Fatal(err)
        }

        fmt.Println("Phone:", result.Phone)
}

NOTE : only package main got binary code

Example : https://blog.laisky.com/p/mgo/,

http://qiita.com/rubytomato@github/items/4192e2340d81c0c39ca5

 

Example simple web go CRUD : https://github.com/GoogleCloudPlatform/appengine-guestbook-go/blob/part4-usingdatastore/hello.go

 

ref : https://golang.org/doc/install,

http://labix.org/mgo

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s