196 Patterns from Automate Your Home Using Go (2024)
196 Patterns from Automate Your Home Using Go (2024)
This 2024 title emphasizes applied systems engineering: Raspberry Pi deployment, Dockerized services, telemetry, monitoring with Prometheus/Grafana, and practical automation workflows.
What This Adds to Our Book
- Strong real-world edge/infrastructure use cases beyond traditional web CRUD.
- Better observability-first mindset for long-running services.
- Helpful pathway from single-node apps to homelab/multi-service operations.
Edge Automation Topology
sensor/input -> Go collector -> local queue/cache -> automation decision -> action
|
+-> metrics/logs -> Prometheus/Grafana
Deep Integration Example: Telemetry Collector with Health and Metrics Surface
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"time"
)
type Reading struct {
Source string `json:"source"`
Value float64 `json:"value"`
At time.Time `json:"at"`
}
type State struct {
mu sync.RWMutex
last map[string]Reading
ingested uint64
}
func newState() *State {
return &State{last: make(map[string]Reading)}
}
func (s *State) ingest(r Reading) {
s.mu.Lock()
defer s.mu.Unlock()
s.last[r.Source] = r
s.ingested++
}
func (s *State) handleIngest(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var x Reading
if err := json.NewDecoder(r.Body).Decode(&x); err != nil {
http.Error(w, "bad payload", http.StatusBadRequest)
return
}
x.At = time.Now().UTC()
s.ingest(x)
w.WriteHeader(http.StatusAccepted)
}
func (s *State) handleHealth(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "ts": time.Now().UTC()})
}
func (s *State) handleMetrics(w http.ResponseWriter, _ *http.Request) {
s.mu.RLock()
defer s.mu.RUnlock()
_, _ = w.Write([]byte("collector_ingested_total "))
_, _ = w.Write([]byte(fmt.Sprintf("%d\n", s.ingested)))
}
func main() {
st := newState()
mux := http.NewServeMux()
mux.HandleFunc("POST /ingest", st.handleIngest)
mux.HandleFunc("GET /healthz", st.handleHealth)
mux.HandleFunc("GET /metrics", st.handleMetrics)
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 2 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}Why This Matters
Practical automation projects force integration of networking, state handling, deployment, and observability. This makes them high-value capstones for Go learners.
Curriculum Upgrades Recommended
- Add an edge/homelab tutorial track under specialized chapters.
- Add observability hooks by default in systems examples.
- Add deployment story from local process -> Docker -> lightweight orchestrated environment.