Building a Microservice with Go and Docker

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting up the Development Environment
  4. Creating the Go Microservice
  5. Building and Running the Microservice
  6. Conclusion


Introduction

In this tutorial, we will learn how to build a microservice using Go and Docker. We will create a simple HTTP server that provides a JSON API. By the end of the tutorial, you will have a basic understanding of building microservices with Go and deploying them in a Docker container.

Prerequisites

To follow along with this tutorial, you should have basic knowledge of Go programming language and familiarity with the command line. You will also need to have Go and Docker installed on your machine.

Setting up the Development Environment

  1. Install Go: Visit the official Go website (https://golang.org/dl/) and download the appropriate installer for your operating system. Follow the installation instructions to complete the installation.

  2. Install Docker: Visit the official Docker website (https://www.docker.com/products/docker-desktop) and download Docker Desktop for your operating system. Follow the installation instructions to complete the installation.

  3. Verify installations: Open a terminal or command prompt and run the following commands to verify that Go and Docker are installed correctly:

    ```shell
    go version
    docker version
    ```
    

Creating the Go Microservice

  1. Create a new directory for your microservice:

    ```shell
    mkdir microservice
    cd microservice
    ```
    
  2. Initialize a new Go module:

    ```shell
    go mod init github.com/your-username/microservice
    ```
    
  3. Create a file named main.go and open it in your preferred text editor. This file will contain the main logic of our microservice.

  4. Import the required packages:

    ```go
    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
        "net/http"
    )
    ```
    
  5. Define a struct to represent our data model. Let’s assume we are building a microservice that manages a list of books:

    ```go
    type Book struct {
        ID     int    `json:"id"`
        Title  string `json:"title"`
        Author string `json:"author"`
    }
    ```
    
  6. Create a slice to store the list of books:

    ```go
    var books []Book
    ```
    
  7. Implement an HTTP handler to handle the GET request and return the list of books as JSON:

    ```go
    func getBooks(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(books)
    }
    ```
    
  8. Create a function to initialize some sample data:

    ```go
    func initBooks() {
        books = append(books, Book{ID: 1, Title: "Book 1", Author: "Author 1"})
        books = append(books, Book{ID: 2, Title: "Book 2", Author: "Author 2"})
        // Add more books as needed
    }
    ```
    
  9. Implement the main function to initialize the sample data, register the HTTP handler, and start the server:

    ```go
    func main() {
        initBooks()
    
        http.HandleFunc("/books", getBooks)
    
        log.Fatal(http.ListenAndServe(":8080", nil))
    }
    ```
    
  10. Save the main.go file.

Building and Running the Microservice

  1. Build the Go executable:

    ```shell
    go build
    ```
    
  2. Run the executable to start the microservice:

    ```shell
    ./microservice
    ```
    
    You should see a log message indicating that the server is running.
    
  3. Open a web browser and visit http://localhost:8080/books. You should see the list of books displayed as JSON.

  4. Press Ctrl+C in the terminal to stop the microservice.

Conclusion

In this tutorial, you learned how to build a microservice using Go and Docker. We created a simple HTTP server that provides a JSON API for managing a list of books. You also learned how to build and run the microservice using Go tools. By containerizing our microservice with Docker, we can easily deploy it to different environments without worrying about dependencies.

You can extend this microservice by adding more API endpoints, implementing data persistence, or integrating with databases. Building microservices with Go and Docker opens up endless possibilities for creating scalable and efficient applications.

Now go ahead and explore more about Go and Docker to expand your knowledge and build even more exciting microservices!


Please note that this tutorial covers the ‘Networking and Web Programming’ and ‘Concurrency’ categories.