Hello World

A sample go program is show here.

package main

import "fmt"

func main() {
  message := greetMe("world")
  fmt.Println(message)
}

func greetMe(name string) string {
  return "Hello, " + name + "!"
}

Run the program as below:

$ go run hello.go
Variables

Normal Declaration:

var msg string
msg = "Hello"

Shortcut:

msg := "Hello"
Constants
const Phi = 1.618
Strings
str := "Hello"

Multiline string

str := `Multiline
string`
Numbers

Typical types

num := 3          // int
num := 3.         // float64
num := 3 + 4i     // complex128
num := byte('a')  // byte (alias for uint8)

Other Types

var u uint = 7        // uint (unsigned)
var p float32 = 22.7  // 32-bit float
Arrays
// var numbers [5]int
numbers := [...]int{0, 0, 0, 0, 0}
Pointers
func main () {
  b := *getPointer()
  fmt.Println("Value is", b)
func getPointer () (myPointer *int) {
  a := 234
  return &a
a := new(int)
*a = 234

Pointers point to a memory location of a variable. Go is fully garbage-collected.

Type Conversion
i := 2
f := float64(i)
u := uint(i)
Slice
slice := []int{2, 3, 4}
slice := []byte("Hello")
Condition
if day == "sunday" || day == "saturday" {
  rest()
} else if day == "monday" && isTired() {
  groan()
} else {
  work()
}
if _, err := doThing(); err != nil {
  fmt.Println("Uh oh")
Switch
switch day {
  case "sunday":
    // cases don't "fall through" by default!
    fallthrough

  case "saturday":
    rest()

  default:
    work()
}
Loop
for count := 0; count <= 10; count++ {
  fmt.Println("My counter is at", count)
}
entry := []string{"Jack","John","Jones"}
for i, val := range entry {
  fmt.Printf("At position %d, the character %s is present\n", i, val)
n := 0
x := 42
for n != x {
  n := guess()
}
Condition
if day == "sunday" || day == "saturday" {
  rest()
} else if day == "monday" && isTired() {
  groan()
} else {
  work()
}
if _, err := doThing(); err != nil {
  fmt.Println("Uh oh")
Set Up SSH Key Authentication
# Generate a new SSH key pair (without passphrase for automation)
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -N ""
# Copy public key to the remote server
ssh-copy-id user@remote_host
Encrypt a File Using OpenSSL
# Encrypt
openssl enc -aes-256-cbc -salt -in myfile.txt -out myfile.txt.enc
# Decrypt
openssl enc -aes-256-cbc -d -in myfile.txt.enc -out myfile.txt
Inspect IP Tables (Firewall Rules)
# List all firewall rules
sudo iptables -L -v -n
# Save current firewall rules
sudo iptables-save > /etc/iptables/rules.v4
View System Logs
# View the latest entries in syslog
tail -f /var/log/syslog
# Or, for more specific logs, use:
journalctl -xe
Monitor Real-Time Network Traffic
sudo iftop  # Needs to be installed; visualizes incoming/outgoing traffic by host
Network Troubleshooting: Check Open Ports
# List all listening ports and their associated services
sudo netstat -tuln
# Or, using `ss` (faster on modern Linux distributions)
sudo ss -tuln
Backup Script with Bash
#!/bin/bash
# backup.sh
SOURCE_DIR="/path/to/source"
DEST_DIR="/path/to/destination"
DATE=$(date +'%Y%m%d')
tar -czvf "${DEST_DIR}/backup_${DATE}.tar.gz" "$SOURCE_DIR"
Update & Clean Up Apt Packages (Debian/Ubuntu)
sudo apt update && sudo apt upgrade -y
sudo apt autoremove -y && sudo apt clean
Check Disk Usage on Linux
# Summary of disk space usage for each filesystem
df -h
# List folder sizes in the current directory
du -sh *
Check System Resource Usage
top
# Or, for a summary
htop  # Provides a better interface if available
Run Container with Limited Resources
# Limit CPU usage to 50% and memory to 256MB
docker run -d --name limited_container --cpus=".5" --memory="256m" myimage
Inspect Container Disk Usage
# Check disk usage of files in a running container
docker exec -it container_name du -h /path/to/dir
Optimize Docker Images with Multi-Stage Builds
# Use a multi-stage build to reduce image size
FROM golang:1.19 AS builder
WORKDIR /app
COPY . .
RUN go build -o main .

FROM alpine:latest
WORKDIR /root/
COPY --from=builder /app/main .
CMD ["./main"]
Clean Up Unused Docker Resources
# Remove unused images, containers, networks, and volumes
docker system prune -a
Log Container Resource Usage
# Monitor resource usage statistics for containers
docker stats
Scale a Deployment
# Scale a deployment to 3 replicas
kubectl scale deployment my-deployment --replicas=3
Debug a Running Pod
# Start a debugging session in a running Pod
kubectl exec -it pod-name -- /bin/sh
Create a Kubernetes Job
# Sample Kubernetes Job configuration
apiVersion: batch/v1
kind: Job
metadata:
  name: example-job
spec:
  template:
    spec:
      containers:
      - name: example
        image: busybox
        command: ["echo", "Hello Kubernetes"]
      restartPolicy: Never
View Cluster Resource Utilization
# Check resource usage for nodes and namespaces
kubectl top nodes
kubectl top pods --namespace=my-namespace
Rolling Update for Deployments
# Update the image version for a deployment with zero downtime
kubectl set image deployment/my-deployment my-container=myimage:v2