Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: be568cb84e
Fetching contributors…

Cannot retrieve contributors at this time

file 81 lines (63 sloc) 1.749 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
// Copyright 2009-2011 The gomongo Authors. All rights reserved.
// Use of this source code is governed by the 3-clause BSD License
// that can be found in the LICENSE file.

package mongo

import (
"fmt"
"io"
"io/ioutil"
"net"
"os"
)


// Default Socket Port
const _PORT = 27017


type Connection struct {
Addr *net.TCPAddr
conn *net.TCPConn
}

func Connect(host string) (*Connection, os.Error) {
return ConnectAt(host, _PORT)
}

/* Creates a new connection to a single MongoDB instance at host:port. */
func ConnectAt(host string, port int) (*Connection, os.Error) {
addr, err := net.ResolveTCPAddr(fmt.Sprintf("%s:%d", host, port))
if err != nil {
return nil, err
}

return ConnectByAddr(addr)
}

func ConnectByAddr(addr *net.TCPAddr) (*Connection, os.Error) {
// Connects from local host (nil)
conn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
return nil, err
}

return &Connection{addr, conn}, nil
}

/* Reconnects using the same address `Addr`. */
func (self *Connection) Reconnect() (*Connection, os.Error) {
connection, err := ConnectByAddr(self.Addr)
if err != nil {
return nil, err
}

return connection, nil
}

/* Disconnects the conection from MongoDB. */
func (self *Connection) Disconnect() os.Error {
if err := self.conn.Close(); err != nil {
return err
}
return nil
}

func (self *Connection) GetDB(name string) *Database {
return &Database{self, name}
}

// === OP_REPLY

/* Gets the message of reply from database. */
func (self *Connection) readReply() (*opReply, os.Error) {
size_bits, _ := ioutil.ReadAll(io.LimitReader(self.conn, 4))
size := pack.Uint32(size_bits)
rest, _ := ioutil.ReadAll(io.LimitReader(self.conn, int64(size)-4))
reply := parseReply(rest)

return reply, nil
}
Something went wrong with that request. Please try again.