• Download
  • Contact
  • Terms of Service
  • Privacy Policy
  • About US
Codershood
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others
No Result
View All Result
Codershood
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others
No Result
View All Result
Codershood
No Result
View All Result

Golang and MongoDB connection tutorial

Learn how to use MognoDB database in Golang Server and fetch data from the MognoDB collection

by Shashank Tiwari
March 10, 2020
in GO lang
0
5 Minutes Read
Golang and MongoDB connection tutorial

This article explains how to connect GoLang to MongoDB. MongoDB is the most popular and widely used open-source Database and as you know Go lang is the new ❤ . When implementing a Web application, MongoDB is one of the necessary bindings to have. In order to Implement GoLang MongoDB connection, you would require GoLang MongoDB driver. This driver will provide the MonngoDB database access to your application and you can perform MonngoDB queries in GoLang.

To demonstrate GoLang MonngoDB connection, I am taking the example of the Ajax Auto-Search Box. Basically, we’ll have a textbox and whatever you will write into it, you will get the response from the server based on the text written inside the textbox.

Since results are already stored in the MonngoDB collection table, So we will be using some kind of MongoDB query to fetch it, we’ll go through that down the road. Here I will be using the plain ES6 Javascript on the client-side, You can use any front-end framework of your choice.




 

 Download

Also read, how to make HTTP(CURL) request in Go lang.

1. Understanding the project structure

1. As I said earlier, here we will create an application, which will imitate the functionality of Ajax Auto Search, in other words, autocomplete functionality. Here we will give a very little bit of styling to our web application just to make it look presentable. Since we are using plain Javascript and there is not much on the client-side to understand, hence we will focus on the Backend part only.

2. Inside the client folder, we will write down the Javascript scripts and inside view folder, we will write down the MARKUP.

Golang mongodb tutorial project Structure

 

 

2. Creating a GoLang Server

1.Create a server.go in the root of the project, which will be our entry point for the project. Here we will make a connection with the MongoDB database and we will define our application routes.

=>Inside the main()function, First we are printing some information.

=>Then using ConnectDatabse()function, we will make a MongoDB connection.

=>In the next line, we will create routevariable, which will hold Route instance.

=>Then AddApproutes() function register application routes.

=>And at the end, using http.ListenAndServe() we will start our GO server.

server.go:

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {

    log.Println("Server will start at http://localhost:8000/")

    ConnectDatabase()

    route := mux.NewRouter()

    AddApproutes(route)

    log.Fatal(http.ListenAndServe(":8000", route))
}

3. Connecting GoLang to MongoDB

1.Create a db.go in the root of the project, Here we will connect our GoLang app with MongoDB database.

=> In the below code, first we have to include the MongoDB Go driver i.e.go-mongodb-driver.

=> Then we have created variable Client, which will hold the MongoDB connection instance. This Clientvariable will be available inside all the files under the main package.

=> Inside theConnectDatabse() function we will create MongoDB connection as shown below,

db.go:

package main

import (
    "context"
    "log"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

// Client is exported Mongo Database client
var Client *mongo.Client

// ConnectDatabase is used to connect the MongoDB database
func ConnectDatabase() {
    log.Println("Database connecting...")
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)
    Client = client
    if err != nil {
        log.Fatal(err)
    }

    // Check the connection
    err = Client.Ping(context.TODO(), nil)

    if err != nil {
        log.Fatal(err)
    }

    log.Println("Database Connected.")
}

4. Adding GoLang routes in the application

1.Create a routes.go in the root of the project, Here we will register application routes. Here we will usegorilla/mux package to register routes.

=>The function setStaticFolder() will tell the GoLang route that /public folder will contain all the static files.

=> Then AddApproutes() function will register all the routes in the application. Here we have only one route to add which will be used by the FrontEnd javascript.

routes.go:

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func setStaticFolder(route *mux.Router) {
    fs := http.FileServer(http.Dir("./public/"))
    route.PathPrefix("/public/").Handler(http.StripPrefix("/public/", fs))
}

// AddApproutes will add the routes for the application
func AddApproutes(route *mux.Router) {

    log.Println("Loadeding Routes...")

    setStaticFolder(route)

    route.HandleFunc("/", RenderHome)

    route.HandleFunc("/users/{name}", GetUsers).Methods("GET")

    log.Println("Routes are Loaded.")
}

5. Using GoLang MySql connection to run MySql queries

1.Create a routes-handlers.go in the root of the project, Here we will create functions which will be called by the routes that we just added in the previous section.

2.In the below code we will write two functions listed below,

  1. RenderHome() will render the html page.
  2. GetUsers() will return the list of users. we have written the MongoDBLIKEquery to fetch the result from Table.
  3. returnErrorResponse() function will return the error response.

=> In the below, using http.ServeFile we are rendering the home page underRenderHome() function.

=> GetUsers() expects two parameters request and response respectively.

=> Then inside GetUsers() function we have created two variables, user and users.

  1. The user variable will hold the instance of the mysql user data inside for loop.
  2. The users variable will hold the array of users.

=> Then we have used MongoDBLike query to fetch the record from the database.

=> Later we have applied for loop on the mysql records in order to fetch the result.

=> And rest of the code is just for error handling.

routes-handlers.go:

package main

import (
    "context"
    "encoding/json"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "go.mongodb.org/mongo-driver/bson"
)

// RenderHome Rendering the Home Page
func RenderHome(response http.ResponseWriter, request *http.Request) {
    http.ServeFile(response, request, "views/index.html")
}

// GetUsers This function will return the response based ono user found in Database
func GetUsers(response http.ResponseWriter, request *http.Request) {
    // Creating  struct for Records
    type User struct {
        Name    string
        Country string
    }
    // Creating Variable of type User struct to hold result from database query
    var results []*User

    // Reading data from the query params
    username := mux.Vars(request)["name"]

    // Getting the instance of the collection from MongoDB Database
    collection := Client.Database("test").Collection("users")

    // Writing query to fetch the Data from the `users` collection
    databaseCursor, err := collection.Find(context.TODO(), bson.M{"name": bson.M{"$regex": username}})

    if err != nil {
        log.Fatal(err)
    }

    // Iterating over the MongoDB Cursor to decode the results
    for databaseCursor.Next(context.TODO()) {
        var elem User
        err := databaseCursor.Decode(&elem)
        if err != nil {
            log.Fatal(err)
        }

        // log.Println(elem.Name, elem.Country)

        // Appending it into the results variable
        results = append(results, &elem)
    }

    if err := databaseCursor.Err(); err != nil {
        log.Fatal(err)
    }

    jsonResponse, jsonError := json.Marshal(results)

    if jsonError != nil {
        log.Fatal(jsonError)
        returnErrorResponse(response, request)
    }

    if jsonResponse == nil {
        returnErrorResponse(response, request)
    } else {
        response.Header().Set("Content-Type", "application/json")
        response.Write(jsonResponse)
    }

}

// Helper function to handle the HTTP response
func returnErrorResponse(response http.ResponseWriter, request *http.Request) {
    jsonResponse, err := json.Marshal("It's not you it's me.")
    if err != nil {
        panic(err)
    }
    response.Header().Set("Content-Type", "application/json")
    response.WriteHeader(http.StatusInternalServerError)
    response.Write(jsonResponse)
}

6. Conclusion

So this was a small demonstration of GoLang and MongoDB database connectivity. In this article, the frontend part was not that interesting, so I did not add the code scripting and Markup here. You will find the whole project when you will download the source code.

Also, comment down below if you have any questions regarding this article. I’ll be happy to help, Till then Happy going 😀.

Tags: Gogo mongodbGo serverGolang and MongodbGoLang CRUDGolang serverMongoDB
Previous Post

Real time private chatting app using React, Nodejs, mongodb and Socket.io – Part 4

Next Post

Serving Static Files in GoLang using Gorilla Mux

Related Posts

Real time private chatting app using React, Golang and mongodb banner-part 2
GO lang

Real time private chatting app using GoLang, React and mongodb – Part 2

July 4, 2020
Real time private chatting app using React, Golang and mongodb banner
GO lang

Real time private chatting app using GoLang, React and Mongodb – Part 1

July 4, 2020
Sending message to specific user with GoLang WebSocket
GO lang

Sending message to specific user with GoLang WebSocket

August 6, 2023
Next Post
Serving Static Files in GoLang using Gorilla Mux

Serving Static Files in GoLang using Gorilla Mux

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *




https://codershood.info

www.codershood.info programming blog dedicated to providing high-quality coding tutorial and articles on web development, Angular, React, Laravel, AngularJs, CSS, Node.js, ExpressJs and many more. We also provide ebook based on complicated web application along with the source code.

  • Download
  • Contact
  • Terms of Service
  • Privacy Policy
  • About US

www.codershood.info is licensed under a Creative Commons Attribution 4.0 International License.

No Result
View All Result
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others

www.codershood.info is licensed under a Creative Commons Attribution 4.0 International License.