Preface

Many say Golang (or just Go) is a very good choice for developing a service for the cloud infrastructure. And that is mostly true. If you have a stateful service that requires a database in the backend, you may find it difficult to setup such cloud infrastructure and to establish a communication between the Go service and the database server.

Fortunately, there are already solutions that simplify our lives. For example, if you want to store your data in MongoDB, you can use MongoDB Atlas — a fully  managed database service in the cloud. We do not explain here, how to setup a MongoDB cluster. It is very well done here. We focus on how to create a connection to MongoDB Atlas with Go and interact with this database cluster.

Prerequisites

You need an account on MongoDB Atlas and a running database cluster. The tier M0 Sandbox would be enough, since it is for free use and allows you to store up to 512MB of data. Please make sure your IP is added to the whitelist in your MongoDB Atlas project (see Security -> Network Access). If you deploy the Go service in a Google Kubernetes Engine, you may want to take a look at our next article, which explains how to securely connect a Kubernetes cluster with the MongoDB Atlas.

Create an empty Go service

Let us create a simple Go service with two endpoints:

  • /save to receive a record and to store it
  • /read to return the previously stored record back

The service will listen on port 8080:

import (
    "net/http"
)

func main() {
    http.HandleFunc("/save", post)
    http.HandleFunc("/read", get)

    if err := http.ListenAndServe(":8080", nil); err != nil {
        panic(err)
    }
}

func post(w http.ResponseWriter, req *http.Request) {}

func get(w http.ResponseWriter, req *http.Request) {}

#golang #tutorial #go #mongodb-atlas

Connect Your Go Service with MongoDB Atlas
6.75 GEEK