How to Create a Web Server in Golang and Connect to MongoDB

Veerasolaiyappan
Cloudnloud Tech Community
4 min readApr 26, 2023

Golang, also known as Go, is a popular programming language that’s widely used for developing high-performance web applications. In this blog, we’ll walk through the process of creating a basic web server in Golang and connecting it to a MongoDB database.

Prerequisites

Before we begin, you’ll need to make sure you have the following tools installed:

Step 1: Setting up the Environment

First, let’s set up the Golang development environment and install the necessary packages.

  1. Create a new directory for your project and open a terminal or command prompt in that directory.
  2. Run the following command to initialize a new Go module:
go mod init <module-name>

Replace <module-name> with the name of your module.

3. Install the MongoDB Go driver by running the following command:

go get go.mongodb.org/mongo-driver/mongo

This will install the latest version of the MongoDB Go driver and its dependencies.

Step 2: Creating a Web Server

Now that we have our development environment set up, let’s create a basic web server using the Golang standard library.

  1. Create a new file called main.go in your project directory.
  2. Add the following code to the file:
package main

import (
"fmt"
"log"
"net/http"
)

func main() {
port := 8000
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to my Golang web server!")
})
fmt.Printf("Server is listening on port %s...\n", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}

This code creates a new HTTP server that listens on port 8080 and responds with a "Welcome" message for any incoming requests.

3. Run the following command to start the server:

go run main.go

You should see a message indicating that the server is running:

Server is listening on port 8080...

Now if you open a web browser and navigate to http://localhost:8080, you should see the "Welcome" message displayed in the browser.

Step 3: Establishing a Connection to MongoDB

Next, let’s connect our Golang web server to a MongoDB database.

  1. Start the MongoDB server by running the following command:
mongod

This will start the MongoDB server on the default port 27017.

2. Add the following code to the main function in main.go to connect to the MongoDB database:

We start by importing the necessary packages:

package main

import (
"context"
"fmt"
"log"
"net/http"

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

We import the following packages:

  • context: for creating contexts that can be used to cancel or timeout requests.
  • fmt: for formatting and printing strings.
  • log: for logging messages to the console.
  • net/http: for creating an HTTP server that can listen for incoming requests.
  • go.mongodb.org/mongo-driver/mongo: for interacting with a MongoDB database.
  • go.mongodb.org/mongo-driver/mongo/options: for specifying options when connecting to a MongoDB database.

We define a main function:

func main() {
// ...
}

This is the entry point of our program.

We connect to a MongoDB database:

clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
log.Fatal("Failed to connect to MongoDB: ", err)
}
defer client.Disconnect(context.Background())

We start by creating a clientOptions variable that specifies the URI of the MongoDB server we want to connect to. In this case, we're connecting to a server running on localhost on port 27017.

We then use the mongo.Connect function to connect to the MongoDB server. If there's an error during the connection, we log a message to the console and exit the program.

Finally, we use the defer statement to ensure that the client is disconnected from the server when the program exits.

We check if the MongoDB connection was successful:

err = client.Ping(context.Background(), nil)
if err != nil {
log.Fatal("Failed to ping MongoDB server: ", err)
} else {
log.Println("Connected to MongoDB!")
}

We use the client.Ping function to check if the MongoDB server is responsive. If there's an error during the ping, we log a message to the console and exit the program.

If the ping is successful, we log a message to the console indicating that the connection to the MongoDB server was successful.

We create a new HTTP server:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to my Golang web server!")
})

We use the http.HandleFunc function to register a handler function for the root path /. When a request is received on the root path, the handler function returns a simple "Welcome" message to the client.

We start the HTTP server:

log.Fatal(http.ListenAndServe(":8080", nil))

We use the http.ListenAndServe function to start the HTTP server and listen for incoming requests on port 8080. If there's an error during the server startup, we log a message to the console and exit the program.

Here is the Final code base

package main

import (
"context"
"fmt"
"log"
"net/http"

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

func main() {
// Connect to MongoDB
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
log.Fatal("Failed to connect to MongoDB: ", err)
}
defer client.Disconnect(context.Background())

// Check if MongoDB connection was successful
err = client.Ping(context.Background(), nil)
if err != nil {
log.Fatal("Failed to ping MongoDB server: ", err)
} else {
log.Println("Connected to MongoDB!")
}

// Create a new HTTP server
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to my Golang web server!")
})

log.Fatal(http.ListenAndServe(":8080", nil))
}

that’s it guys. we created the web server and established the Mongodb connection

Hope this article is helpful to you

Follow Veerasolaiyappan and Cloudnloud Tech Community for more insightful knowledge & resources & free learning

--

--