Building simple blog API with Golang + Mongodb (part 1)

Kyaw Myint Thein
Mar 22, 2016 · 4 min read

This article is about building simple blog API with Golang and mongodb. It will include building Restful API with Golang (Beego) and Mongodb for database. It is basic skeleton for Restful API. So, you can also apply for your project.

In this article, I wanna talk about mainly for working Mongodb with Golang, Beego framework for Restful API, Error handling and so on.

Firstly, I want to share about beego framework a bit.

Beego is a web framework for Golang. In beego, you can build web application and Restful API. This time, I wanna talk about Beego API. If you want to know about beego in detail, please checkout this link http://beego.me/.

Beego include command line tools called “bee” to generate and scaffold the file and project skeleton. You can also use “bee” command to run the beego project.

This time I don’t want explain about how to install golang in this article. So, let start with installing Beego framework.

At first, Use following command to install beego and bee tools in your computer.

go get -u github.com/beego/bee
go get -u github.com/astaxie/beego

Then, go to $GOPATH/src and use “bee tools” to scaffold beego api skeleton. Use following command to scaffold “blog_api”.

bee api blog_api

Now you can find blog_api project under $GOPATH/src. Use following command to run the project.

cd blog_api && bee run -downdoc=true -gendoc=true

Beego use “Swagger” for api documentation. “-downdoc=true” command will automatically download swagger folder in your project and “-gendoc=true” is to generate api documentation. Now you can open the following link to see your project is runing.

http://127.0.0.1:8080/swagger/swagger-1/

Now your project is running on port 8080 by default.

Beego is also MVC framework. Following image is beego api project folder structure. conf folder includes app.conf file for configuration. You can create controller in controllers folders and models also. routers include router.rb to specify the route for your controller. docs is for api documentation. It also include tests folder for test cases.

For this article, I wanna build simple blog api by using Mongodb for database. So, we need to connect Beego and mongodb database.

For mongodb, I will use https://labix.org/mgo golang library. Before you use that library, you need install golang package in your computer. You can install by using “go get” command as follow.

go get gopkg.in/mgo.v2

Then, we can use that library to connect the mongodb database in your local machine. Before we start building blog api, we need to create some basic implementation for mongodb database connection.

After, create db folder in your models folder as below.

At first, we will create service.go under db folder.

package db

import “gopkg.in/mgo.v2”

type Service struct {
baseSession *mgo.Session
queue chan int
URL string
Open int
}

var service Service

func (s *Service) New() error {
var err error
s.queue = make(chan int, maxPool)
for i := 0; i < maxPool; i = i + 1 {
s.queue <- 1
}
s.Open = 0
s.baseSession, err = mgo.Dial(s.URL)
return err
}

func (s *Service) Session() *mgo.Session {
<-s.queue
s.Open++
return s.baseSession.Copy()
}

func (s *Service) Close(c *Collection) {
c.db.s.Close()
s.queue <- 1
s.Open —
}

In service.go, there are 3 functions such as creating new mongo session, get session and closing session.

Then, we will create database.go.

package db

import “gopkg.in/mgo.v2”

type Database struct {
s *mgo.Session
name string
session *mgo.Database
}

func (db *Database) Connect() {
db.s = service.Session()
session := *db.s.DB(db.name)
db.session = &session
}

func newDBSession(name string) *Database {
var db = Database{
name: name,
}
db.Connect()
return &db
}

In database.go, there are 2 main functions to connect the mongodb database by using mongo session from service.go.

After that, we will also need to create driver.go

package db

import “github.com/astaxie/beego”

var maxPool int

func init() {
var err error
maxPool, err = beego.AppConfig.Int(“DBMaxPool”)
if err != nil {
// todo: panic!!!
// panic(err)
println(err)
}
// init method to start db
checkAndInitServiceConnection()
}

func checkAndInitServiceConnection() {
if service.baseSession == nil {
service.URL = beego.AppConfig.String(“DBPath”)
err := service.New()
if err != nil {
// todo: panic!!!
// panic(err)
println(err)
}
}
}

In driver.go, there is one function which is responsible to check the mongo session with service.go and create new session. In this file, we read some configuration from app.conf. (example. beego.AppConfig.String(“DBPath”)). So, you need to create DBPath in app.conf file as follow.

appname = blog_api
httpport = 8080
runmode = dev
autorender = false
copyrequestbody = true
EnableDocs = true
EnableDocs = true
DBPath = “localhost”
DBMaxPool = 30
DBName = “blog_api”

Then, we also need to create collection.go file

package db

import (
“github.com/astaxie/beego”
“gopkg.in/mgo.v2”
)

type Collection struct {
db *Database
name string
Session *mgo.Collection
}

func (c *Collection) Connect() {
session := *c.db.session.C(c.name)
c.Session = &session
}

func NewCollectionSession(name string) *Collection {
var c = Collection{
db: newDBSession(beego.AppConfig.String(“DBName”)),
name: name,
}
c.Connect()
return &c
}

func (c *Collection) Close() {
service.Close(c)
}

collection.go is to connect to get new session for mongodb collections.

Now it is ready to use in your model for mongodb as database. I will continues as part 2 for using that function in builidng blog api.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade