0

I am Golang beginner so sorry If my question is stupid :| I created a class to access simply Database (MongoDB)

package network

import (
    "bytes"
    "gopkg.in/mgo.v2"
)

type DatabaseConfig struct {
    Host        string  `yaml:mongo_db_host`
    Port        string  `yaml:mongo_db_port`
    Name        string  `yaml:mongo_db_name`
    Username    string  `yaml:mongo_db_user`
    Password    string  `yaml:mongo_db_pass`
}

type Database struct {
    Session     *mgo.Session
    Config      DatabaseConfig
    IsOpen      bool
}

func (d Database) NewSession() error {
    url := bytes.Buffer{}
    url.WriteString("mongodb://")

    if d.Config.Username != "" && d.Config.Password != "" {
        url.WriteString(d.Config.Username)
        url.WriteString(":")
        url.WriteString(d.Config.Password)
        url.WriteString("@")
    }
    if d.Config.Host != "" {
        url.WriteString(d.Config.Host)
    }
    if d.Config.Port != "" {
        url.WriteString(":")
        url.WriteString(d.Config.Port)
    }
    if d.Config.Name != "" {
        url.WriteString("/")
        url.WriteString(d.Config.Name)
    }

    var err error
    d.Session, err = mgo.Dial(url.String())
    if err == nil {
        d.IsOpen = true
    }

    return err
}

func (d Database) GetSession() *mgo.Session {
    return d.Session
}

func (d Database) CloseSession() {
    d.Session.Close()
    d.IsOpen = false
}

func (d Database) GetConfig() DatabaseConfig {
    return d.Config
}

func (d Database) SetConfig(config DatabaseConfig) {
    d.Config = config   
}

I create a new db like this:

db_config := network.DatabaseConfig{
    Host: "localhost",
    Port: "27017",
    Name: "meuporg",
}
db := network.Database{}
db.SetConfig(db_config)

err = db.NewSession()
log.Fatal(db.GetSession())

glbContainer.DB = db

And each time it builds and returns me "nil", I tried to log db.Session inside the function and this returns me the correct structure.

I think I am doing something wrong with pointers but I don't see what. Can you help me understanding what is going wrong ? Thanks :)

Nada3
  • 1
  • You're using a value receiver which means the methods on it cannot modify the object. You need to use a pointer receiver instead: `func (d *Database) NewSession() error`. Please see the duplicate question for more details. – Marc Feb 10 '18 at 10:00
  • Thanks a lot for your answer I juste saw that.sorry for making you waste your time :( – Nada3 Feb 10 '18 at 10:02
  • Aside: use the net/url package to build URLs. – Peter Feb 10 '18 at 10:22

0 Answers0