Continuous Integration (CI) pipelines are essential for modern software development, ensuring that code changes are automatically tested and integrated. This article explores a real-world example of building a CI pipeline for a Go application, incorporating integration tests and Docker Compose.

Setting Up the Go Application

The first step involves creating a simple Go application. This application will be the target of our CI pipeline, and it includes basic functionality along with integration tests.

Here's a basic example of a Go server:

package main

import ("fmt" "net/http")

func main() {

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

fmt.Fprintln(w, "Hello, World!")

})

http.ListenAndServe(":8080", nil)

}

Writing Integration Tests in Go

Integration tests verify that different parts of the application work together as expected. In Go, these tests often involve running the server and making HTTP requests to it.

Example of an integration test:

package main

import ("net/http" "testing")

func TestServerResponse(t *testing.T) {

resp, err := http.Get("http://localhost:8080/")

if err != nil {

t.Fatalf("Failed to send GET request: %v", err)

}

if resp.StatusCode != 200 {

t.Errorf("Expected status 200, got %d", resp.StatusCode)

}

}

Using Docker Compose for Environment Management

Docker Compose simplifies running the application and its dependencies. We define a docker-compose.yml file to orchestrate the environment.

Example docker-compose.yml:

version: "3"

services:

app:

build: .

ports:

- "8080:8080"

db:

image: postgres

Integrating the Pipeline

In our CI pipeline, we automate the process of building the Go application, running Docker Compose to start the environment, executing tests, and then tearing down the environment.

Sample CI steps:

  • Build the Go application: go build
  • Start Docker Compose: docker-compose up -d
  • Run integration tests: go test ./...
  • Stop Docker Compose: docker-compose down

Conclusion

This example demonstrates how to combine Go integration tests with Docker Compose to create a robust CI pipeline. Automating these steps ensures consistent testing environments and reliable deployments.