Welcome to the world of DevOps! ? Today, I’m back with another exciting blog to help you dive deeper into practical programming for DevOps tasks. In my previous blog, we explored 3 Python projects that laid the foundation for DevOps automation.
Now, let’s switch gears and explore the power of Go-lang! This blog will guide you through building 3 Go-lang projects that are both practical and beginner-friendly:
So, grab your favorite code editor, and let’s get started! ?
Before we dive into building these projects, let’s make sure your environment is set up and ready to go. Here’s what you need:
1. Go (Golang)
You’ll need to have Go installed on your system. Follow these steps based on your operating system:
Windows
go version
Ubuntu
sudo apt update sudo apt install -y golang
go version
macOS
brew install go
go version
2. Basic Understanding of Go
While you don’t need to be an expert, having a fundamental understanding of Go concepts like variables, functions, and structs will help you follow along smoothly. If you’re new to Go, I recommend exploring the Go Tour for a quick introduction.
With these prerequisites met, you’re all set to start building these awesome Go-lang projects! ?
Let’s kick off our journey with the first project — a disk usage monitoring tool. This program will help you analyze disk usage for any specified directory on your system.
You can find the source code in my GitHub repository. Let’s start by creating a file named disk_usage.go and adding the following code:
package main import ( "fmt" "os" "syscall" ) func getDiskUsage(path string) { var stat syscall.Statfs_t err := syscall.Statfs(path, &stat) if err != nil { fmt.Println("Error Fetching Disk Usage:", err) return } total := stat.Blocks * uint64(stat.Bsize) free := stat.Bfree * uint64(stat.Bsize) used := total - free percentUsed := float64(used) / float64(total) * 100 fmt.Printf("Disk usage of %s:\n", path) fmt.Printf("Total: %d GB\n", total/1e9) fmt.Printf("Used: %d GB (%.2f%%)\n", used/1e9, percentUsed) fmt.Printf("Free: %d GB\n", free/1e9) } func main() { path := "/" if len(os.Args) > 1 { path = os.Args[1] } _, err := os.Stat(path) if os.IsNotExist(err) { fmt.Printf("Error: '%s' Path doesn't exist.\n", path) return } else if err != nil { fmt.Printf("Error occurred while accessing path %s: %v \n", path, err) return } getDiskUsage(path) }
How the Program Works:
Running the Program
To run the program, use the following commands:
go version
sudo apt update sudo apt install -y golang
Since I have a single partition, I will get the same result if I provide different paths.
This project demonstrates how Go can interact with your system’s underlying APIs, making it a great starting point for system monitoring tasks. ?
The second project involves creating an HTTP server in Go that hosts a portfolio website. This project demonstrates how you can build and serve static websites while incorporating a health check endpoint for monitoring.
You can find the source code in my GitHub repository.
Steps to Build the HTTP Server
go version
How It Works
Creating the Portfolio Website
Structure: Inside the static folder, create:
Add the following content to your files:
index.html:
brew install go
Running the Program
go version
Accessing the Health Check
To check the health of the server, visit:
package main import ( "fmt" "os" "syscall" ) func getDiskUsage(path string) { var stat syscall.Statfs_t err := syscall.Statfs(path, &stat) if err != nil { fmt.Println("Error Fetching Disk Usage:", err) return } total := stat.Blocks * uint64(stat.Bsize) free := stat.Bfree * uint64(stat.Bsize) used := total - free percentUsed := float64(used) / float64(total) * 100 fmt.Printf("Disk usage of %s:\n", path) fmt.Printf("Total: %d GB\n", total/1e9) fmt.Printf("Used: %d GB (%.2f%%)\n", used/1e9, percentUsed) fmt.Printf("Free: %d GB\n", free/1e9) } func main() { path := "/" if len(os.Args) > 1 { path = os.Args[1] } _, err := os.Stat(path) if os.IsNotExist(err) { fmt.Printf("Error: '%s' Path doesn't exist.\n", path) return } else if err != nil { fmt.Printf("Error occurred while accessing path %s: %v \n", path, err) return } getDiskUsage(path) }
This project showcases how to use Go-lang to create a functional web server for hosting static content, with additional monitoring through a health check endpoint. ?
In the final project of this blog, we’ll create a RESTful API that allows you to manage a list of DevOps tools. This program demonstrates the use of Go’s net/http package to handle RESTful routes and manage data.
The complete source code is available on my GitHub repository.
Building the RESTful API
Step 1: Main Program
Create a file named main.go and add the following code:
go version
Step 2: Data Handling
In the tools directory, create a file named data.go and add:
sudo apt update sudo apt install -y golang
Step 3: Handlers
In the tools directory, create another file named handler.go and add:
go version
Initializing the Module
Before running the program, initialize the Go module:
brew install go
This ensures the project can use the project/tools package.
Running the Program
Start the server by running:
go version
Testing the API
package main import ( "fmt" "os" "syscall" ) func getDiskUsage(path string) { var stat syscall.Statfs_t err := syscall.Statfs(path, &stat) if err != nil { fmt.Println("Error Fetching Disk Usage:", err) return } total := stat.Blocks * uint64(stat.Bsize) free := stat.Bfree * uint64(stat.Bsize) used := total - free percentUsed := float64(used) / float64(total) * 100 fmt.Printf("Disk usage of %s:\n", path) fmt.Printf("Total: %d GB\n", total/1e9) fmt.Printf("Used: %d GB (%.2f%%)\n", used/1e9, percentUsed) fmt.Printf("Free: %d GB\n", free/1e9) } func main() { path := "/" if len(os.Args) > 1 { path = os.Args[1] } _, err := os.Stat(path) if os.IsNotExist(err) { fmt.Printf("Error: '%s' Path doesn't exist.\n", path) return } else if err != nil { fmt.Printf("Error occurred while accessing path %s: %v \n", path, err) return } getDiskUsage(path) }
Output:
go run disk_usage.go /path/to/directory
go run disk_usage.go
Output:
package main import ( "fmt" "net/http" ) func healthCheckHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) } func main() { fs := http.FileServer(http.Dir("./static")) http.Handle("/", fs) http.HandleFunc("/health", healthCheckHandler) port := "8090" fmt.Printf("Starting server on port %s....", port) err := http.ListenAndServe(":"+port, nil) if err != nil { fmt.Println("Error starting server:", err) } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Pravesh Sudha - Portfolio</title> <link rel="stylesheet" href="style.css"> </head> <body> <header> <div> <p><strong>style.css:</strong><br> </p> <pre class="brush:php;toolbar:false">body { font-family: Arial, sans-serif; margin: 0; padding: 0; line-height: 1.6; color: #333; background-color: #f9f9f9; } header { background: #4caf50; color: #fff; padding: 20px 0; text-align: center; } header .profile-picture { width: 150px; height: 150px; border-radius: 50%; margin-bottom: 15px; } header h1 { font-size: 2.5em; margin: 0; } header .subtitle { font-size: 1.2em; margin: 0; } main { padding: 20px; max-width: 800px; margin: 20px auto; background: #fff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); } main .about, main .links { margin-bottom: 20px; } main .links ul { list-style: none; padding: 0; } main .links li { margin: 10px 0; } main .links a { color: #4caf50; text-decoration: none; font-weight: bold; } main .links a:hover { text-decoration: underline; } footer { text-align: center; padding: 10px 0; background: #333; color: #fff; }
Output:
go run http_server.go
In this blog, we’ve explored three practical Go projects that help you get hands-on experience with different aspects of software development. From monitoring disk usage to building a simple HTTP server to hosting a portfolio website, and finally, creating a RESTful API to manage DevOps tools, these projects provide a solid foundation for anyone looking to sharpen their Go programming skills.
Each of these projects is a building block that can be expanded upon to suit real-world applications. Whether you are interested in monitoring systems, developing web applications, or building APIs, Go provides the simplicity and power needed for efficient development.
? For more informative blog, Follow me on Hashnode, X(Twitter) and LinkedIn.
Till then, Happy Coding!!
Happy Learning! ?
The above is the detailed content of xciting Go-lang Projects to Kickstart Your DevOps Journey. For more information, please follow other related articles on the PHP Chinese website!