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.
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.
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 route
variable, 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 Client
variable 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,
RenderHome()
will render the html page.GetUsers()
will return the list of users. we have written the MongoDBLIKE
query to fetch the result from Table.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.
- The
user
variable will hold the instance of the mysql user data inside for loop. - 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 😀.