TExcelTAD

The CI Workflow

linkly's pipeline has one job per question a reviewer would ask: Is it formatted and vetted? Do the tests pass, against real databases too? Does it call known-vulnerable code? Does the image have known vulnerabilities? Can I deploy exactly what was tested? The CI/CD course teaches GitHub Actions and pipeline security in depth; this lesson applies it to one service, starting from a rule that saves hours of debugging:

The pipeline calls make, and make is what you run locally. If CI runs commands you can't run on your laptop, every failure becomes a push-and-wait loop.

The Makefile

make
VERSION ?= $(shell git describe --tags --always --dirty)
LDFLAGS := -s -w -X main.version=$(VERSION)

.PHONY: ci lint test integration vuln build scan

ci: lint test integration vuln build scan

lint:
	@test -z "$(gofmt -l .)" || { echo "gofmt needed:"; gofmt -l .; exit 1; }
	go vet ./...

test:
	go test -race ./...

integration:
	go test -race -tags integration -run WithPostgres ./...

vuln:
	govulncheck ./...

build:
	CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o dist/linkly .
	@echo "built dist/linkly $(VERSION)"

scan:
	trivy fs -q --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 .

VERSION comes from git describe: v1.4.0 on a tag, v1.4.0-3-gabc1234 three commits later, with -dirty if the working tree has uncommitted changes. The binary, the image tag and linkly_build_info all carry it, so any running pod can be traced back to a commit. (Versioning covers the scheme.)

A local rehearsal

The session recreates linkly with its tests, adds the Makefile, Dockerfile and .trivyignore from the container lesson, commits and tags v1.4.0, and runs make ci against PostgreSQL and Redis started in the session, exactly the steps the workflow below runs. Then it breaks formatting on purpose to see a gate fail:

bash · try it yourself
initdb -D pgdata -U linkly --auth=trust >/dev/null
mkdir -p pgrun
pg_ctl -D pgdata -o "-k /home/learner/pgrun -c listen_addresses=" -l pg.log start >/dev/null
createdb linkly
redis-server --port 6379 --bind 127.0.0.1 --daemonize yes --dir /home/learner
mkdir linkly && cd linkly
cat > main.go <<'EOF'
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/redis/go-redis/v9"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)

// version is stamped at build time: go build -ldflags "-X main.version=1.4.0"
var version = "dev"

type config struct {
	Addr, DatabaseURL, RedisAddr, BaseURL, LogLevel, Traces string
	CacheTTL, ShutdownGrace                                 time.Duration
}

func env(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}

// loadConfig reads the twelve-factor configuration from the environment.
func loadConfig() (config, error) {
	c := config{
		Addr:        env("LISTEN_ADDR", ":8080"),
		DatabaseURL: env("DATABASE_URL", ""),
		RedisAddr:   env("REDIS_ADDR", "localhost:6379"),
		BaseURL:     env("BASE_URL", "http://localhost:8080"),
		LogLevel:    env("LOG_LEVEL", "info"),
		Traces:      env("OTEL_TRACES_EXPORTER", "none"),
	}
	var err error
	if c.CacheTTL, err = time.ParseDuration(env("CACHE_TTL", "1h")); err != nil {
		return c, fmt.Errorf("CACHE_TTL: %w", err)
	}
	if c.ShutdownGrace, err = time.ParseDuration(env("SHUTDOWN_GRACE", "10s")); err != nil {
		return c, fmt.Errorf("SHUTDOWN_GRACE: %w", err)
	}
	if c.DatabaseURL == "" {
		return c, errors.New("DATABASE_URL is required")
	}
	return c, nil
}

func main() {
	cfg, err := loadConfig()
	var level slog.Level
	if err == nil {
		err = level.UnmarshalText([]byte(cfg.LogLevel))
	}
	log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
	if err == nil {
		err = run(cfg, log)
	}
	if err != nil {
		log.Error("linkly stopped", "err", err)
		os.Exit(1)
	}
}

func run(cfg config, log *slog.Logger) error {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	shutdownTracing, err := setupTracing(cfg.Traces, os.Stderr)
	if err != nil {
		return err
	}
	defer shutdownTracing(context.Background())

	db, err := pgxpool.New(ctx, cfg.DatabaseURL)
	if err != nil {
		return fmt.Errorf("database: %w", err)
	}
	defer db.Close()
	if err := migrate(ctx, db); err != nil {
		return fmt.Errorf("migrate: %w", err)
	}
	redis.SetLogger(redisLogger{log})
	rdb := newRedis(cfg.RedisAddr)
	defer rdb.Close()

	app := newApp(pgStore{db}, rdb, cfg, log, prometheus.DefaultRegisterer, prometheus.DefaultGatherer)
	srv := &http.Server{Addr: cfg.Addr, Handler: app.Handler(), ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second}
	errc := make(chan error, 1)
	go func() {
		log.Info("listening", "addr", cfg.Addr, "version", version)
		errc <- srv.ListenAndServe()
	}()
	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
	}
	log.Info("shutting down", "grace", cfg.ShutdownGrace.String())
	app.draining.Store(true) // /readyz now answers 503
	sctx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownGrace)
	defer cancel()
	if err := srv.Shutdown(sctx); err != nil {
		return err
	}
	log.Info("stopped")
	return nil
}

// newRedis takes host:port or a redis:// or rediss:// (TLS) URL. The short timeouts keep
// the cache from slowing requests down when Redis is unwell.
func newRedis(addr string) *redis.Client {
	opt, err := redis.ParseURL(addr)
	if err != nil {
		opt = &redis.Options{Addr: addr}
	}
	opt.DialTimeout, opt.DialerRetries, opt.MaxRetries = time.Second, 1, 1
	opt.ReadTimeout, opt.WriteTimeout = 300*time.Millisecond, 300*time.Millisecond
	return redis.NewClient(opt)
}

// redisLogger sends go-redis's own messages to the JSON log instead of plain stderr.
type redisLogger struct{ log *slog.Logger }

func (r redisLogger) Printf(ctx context.Context, format string, v ...any) {
	r.log.WarnContext(ctx, fmt.Sprintf(format, v...), "component", "go-redis")
}

// setupTracing installs the OpenTelemetry SDK; "console" writes spans as JSON to w.
func setupTracing(exporter string, w io.Writer) (func(context.Context) error, error) {
	res := resource.NewSchemaless(semconv.ServiceName("linkly"), semconv.ServiceVersion(version))
	opts := []sdktrace.TracerProviderOption{sdktrace.WithResource(res)}
	switch exporter {
	case "none":
	case "console":
		exp, err := stdouttrace.New(stdouttrace.WithWriter(w))
		if err != nil {
			return nil, err
		}
		opts = append(opts, sdktrace.WithSyncer(exp))
	default:
		return nil, fmt.Errorf("OTEL_TRACES_EXPORTER=%q: this build supports none and console", exporter)
	}
	tp := sdktrace.NewTracerProvider(opts...)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.TraceContext{})
	return tp.Shutdown, nil
}
EOF
cat > app.go <<'EOF'
package main

import (
	"context"
	"crypto/rand"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"net/url"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync/atomic"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/redis/go-redis/v9"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/otel/attribute"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
	"go.opentelemetry.io/otel/trace"
)

type App struct {
	store    Store
	cache    *redis.Client
	ttl      time.Duration
	baseURL  string
	log      *slog.Logger
	newCode  func() string
	draining atomic.Bool
	metrics  http.Handler

	requests  *prometheus.CounterVec
	duration  *prometheus.HistogramVec
	cacheReqs *prometheus.CounterVec
	created   prometheus.Counter
}

func newApp(store Store, cache *redis.Client, cfg config, log *slog.Logger,
	reg prometheus.Registerer, g prometheus.Gatherer) *App {
	f := promauto.With(reg)
	a := &App{store: store, cache: cache, ttl: cfg.CacheTTL, baseURL: cfg.BaseURL, log: log,
		newCode: randomCode, metrics: promhttp.HandlerFor(g, promhttp.HandlerOpts{}),
		requests: f.NewCounterVec(prometheus.CounterOpts{Name: "http_requests_total",
			Help: "HTTP requests by route and status code."}, []string{"route", "code"}),
		duration: f.NewHistogramVec(prometheus.HistogramOpts{Name: "http_request_duration_seconds",
			Help:    "Time to handle a request, by route.",
			Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5}}, []string{"route"}),
		cacheReqs: f.NewCounterVec(prometheus.CounterOpts{Name: "linkly_cache_requests_total",
			Help: "Redis lookups for redirects, by result (hit, miss, error)."}, []string{"result"}),
		created: f.NewCounter(prometheus.CounterOpts{Name: "linkly_links_created_total",
			Help: "Short links created."}),
	}
	f.NewGaugeVec(prometheus.GaugeOpts{Name: "linkly_build_info", Help: "Always 1; labels describe the build."},
		[]string{"version", "goversion"}).WithLabelValues(version, runtime.Version()).Set(1)
	return a
}

func (a *App) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /links", a.createLink)
	mux.HandleFunc("GET /{code}", a.redirect)
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok\n")) })
	mux.HandleFunc("GET /readyz", a.readyz)
	mux.Handle("GET /metrics", a.metrics)
	notProbe := func(r *http.Request) bool { return !quiet(r.URL.Path) }
	return otelhttp.NewHandler(a.observe(mux), "linkly", otelhttp.WithFilter(notProbe))
}

func quiet(route string) bool {
	return route == "/healthz" || route == "/readyz" || route == "/metrics"
}

// observe records metrics, names the trace span and logs every request, all by route template.
func (a *App) observe(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(rec, r)
		route := "unmatched" // r.Pattern is "GET /{code}" once the mux has matched, "" otherwise
		if _, p, ok := strings.Cut(r.Pattern, " "); ok {
			route = p
		}
		a.requests.WithLabelValues(route, strconv.Itoa(rec.status)).Inc()
		a.duration.WithLabelValues(route).Observe(time.Since(start).Seconds())
		span := trace.SpanFromContext(r.Context())
		span.SetName(r.Method + " " + route)
		span.SetAttributes(semconv.HTTPRoute(route))
		level := slog.LevelInfo
		if quiet(route) {
			level = slog.LevelDebug
		} else if rec.status >= 500 {
			level = slog.LevelError
		}
		a.log.LogAttrs(r.Context(), level, "request", slog.String("method", r.Method),
			slog.String("route", route), slog.Int("status", rec.status),
			slog.String("trace_id", span.SpanContext().TraceID().String()))
	})
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) { s.status = code; s.ResponseWriter.WriteHeader(code) }

var codeRE = regexp.MustCompile(`^[A-Za-z0-9_-]{3,32}

  
    
    
    The CI Workflow - DevOps Capstone: Ship a Production Service · ExcelTAD
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  
  
    )

const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

// randomCode returns 7 random characters from a 64-letter alphabet (b&63 has no modulo bias).
// They come from crypto/rand, so codes can't be predicted.
func randomCode() string {
	b := make([]byte, 7)
	if _, err := rand.Read(b); err != nil {
		panic(err) // the OS random source failed: nothing sensible is left to do
	}
	for i := range b {
		b[i] = alphabet[b[i]&63]
	}
	return string(b)
}

func validateURL(raw string) error {
	if len(raw) > 2048 {
		return errors.New("url is longer than 2048 bytes")
	}
	u, err := url.Parse(raw)
	if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
		return errors.New("url must be an absolute http or https URL")
	}
	return nil
}

func (a *App) createLink(w http.ResponseWriter, r *http.Request) {
	var req struct{ URL, Code string }
	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": `body must be JSON like {"url": "https://..."}`})
		return
	}
	if err := validateURL(req.URL); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
		return
	}
	if req.Code != "" && !codeRE.MatchString(req.Code) {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "code must be 3-32 of A-Z a-z 0-9 _ -"})
		return
	}
	code := req.Code
	for attempt := 1; ; attempt++ {
		if req.Code == "" {
			code = a.newCode()
		}
		err := a.store.Create(r.Context(), code, req.URL)
		if err == nil {
			break
		}
		if errors.Is(err, ErrExists) && req.Code == "" && attempt < 3 {
			continue // a random code collided: draw again
		}
		if errors.Is(err, ErrExists) {
			writeJSON(w, http.StatusConflict, map[string]string{"error": "code already taken"})
			return
		}
		a.fail(w, r, err)
		return
	}
	a.created.Inc()
	writeJSON(w, http.StatusCreated, map[string]string{"code": code, "short_url": a.baseURL + "/" + code, "url": req.URL})
}

// redirect reads through the cache: Redis first, PostgreSQL on a miss (or when Redis is down).
func (a *App) redirect(w http.ResponseWriter, r *http.Request) {
	code, ctx := r.PathValue("code"), r.Context()
	if !codeRE.MatchString(code) {
		http.NotFound(w, r)
		return
	}
	key := "link:" + code
	target, err := a.cache.Get(ctx, key).Result()
	result := "hit"
	if errors.Is(err, redis.Nil) {
		result = "miss"
	} else if err != nil {
		result = "error"
		a.log.WarnContext(ctx, "cache read failed", "err", err)
	}
	a.cacheReqs.WithLabelValues(result).Inc()
	trace.SpanFromContext(ctx).SetAttributes(attribute.String("linkly.cache", result))
	if result != "hit" {
		if target, err = a.store.Get(ctx, code); errors.Is(err, ErrNotFound) {
			http.NotFound(w, r)
			return
		} else if err != nil {
			a.fail(w, r, err)
			return
		}
		if err := a.cache.Set(ctx, key, target, a.ttl).Err(); err != nil {
			a.log.WarnContext(ctx, "cache write failed", "err", err)
		}
	}
	http.Redirect(w, r, target, http.StatusFound)
}

// readyz fails only on the database: without Redis, linkly is slower but still correct.
func (a *App) readyz(w http.ResponseWriter, r *http.Request) {
	if a.draining.Load() {
		writeJSON(w, http.StatusServiceUnavailable, map[string]string{"status": "draining"})
		return
	}
	ctx, cancel := context.WithTimeout(r.Context(), time.Second)
	defer cancel()
	res, code := map[string]string{"status": "ready", "database": "up", "cache": "up"}, http.StatusOK
	if err := a.store.Ping(ctx); err != nil {
		a.log.WarnContext(ctx, "readiness: database", "err", err)
		res["status"], res["database"], code = "unavailable", "down", http.StatusServiceUnavailable
	}
	if err := a.cache.Ping(ctx).Err(); err != nil {
		a.log.WarnContext(ctx, "readiness: cache", "err", err)
		res["cache"] = "down"
	}
	writeJSON(w, code, res)
}

func (a *App) fail(w http.ResponseWriter, r *http.Request, err error) {
	a.log.ErrorContext(r.Context(), "request failed", "err", err)
	writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
}

func writeJSON(w http.ResponseWriter, code int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(v)
}
EOF
cat > store.go <<'EOF'
package main

import (
	"context"
	"errors"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"
)

var (
	ErrNotFound = errors.New("link not found")
	ErrExists   = errors.New("code already exists")
)

// Store is where links live; pgStore in production, an in-memory fake in unit tests.
type Store interface {
	Create(ctx context.Context, code, url string) error
	Get(ctx context.Context, code string) (string, error)
	Ping(ctx context.Context) error
}

const schema = `CREATE TABLE IF NOT EXISTS links (
  code       text PRIMARY KEY,
  url        text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now())`

func migrate(ctx context.Context, db *pgxpool.Pool) error {
	_, err := db.Exec(ctx, schema)
	return err
}

type pgStore struct{ db *pgxpool.Pool }

func (s pgStore) Create(ctx context.Context, code, url string) error {
	_, err := s.db.Exec(ctx, `INSERT INTO links (code, url) VALUES ($1, $2)`, code, url)
	var pgErr *pgconn.PgError
	if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation
		return ErrExists
	}
	return err
}

func (s pgStore) Get(ctx context.Context, code string) (string, error) {
	var url string
	err := s.db.QueryRow(ctx, `SELECT url FROM links WHERE code = $1`, code).Scan(&url)
	if errors.Is(err, pgx.ErrNoRows) {
		return "", ErrNotFound
	}
	return url, err
}

func (s pgStore) Ping(ctx context.Context) error { return s.db.Ping(ctx) }
EOF
cat > app_test.go <<'EOF'
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/alicebob/miniredis/v2"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/testutil"
	"github.com/redis/go-redis/v9"
)

// memStore is the in-memory fake Store for unit tests.
type memStore struct {
	mu    sync.Mutex
	links map[string]string
	down  bool
}

func (m *memStore) Create(_ context.Context, code, url string) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	if _, ok := m.links[code]; ok {
		return ErrExists
	}
	m.links[code] = url
	return nil
}

func (m *memStore) Get(_ context.Context, code string) (string, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	if url, ok := m.links[code]; ok {
		return url, nil
	}
	return "", ErrNotFound
}

func (m *memStore) Ping(context.Context) error {
	if m.down {
		return errors.New("connection refused")
	}
	return nil
}

func newTestApp(t *testing.T) (*App, *memStore, *miniredis.Miniredis, *prometheus.Registry) {
	mr := miniredis.RunT(t)
	store := &memStore{links: map[string]string{}}
	reg := prometheus.NewRegistry()
	log := slog.New(slog.NewJSONHandler(io.Discard, nil))
	redis.SetLogger(redisLogger{log})
	cfg := config{BaseURL: "https://lnk.test", CacheTTL: time.Hour}
	a := newApp(store, newRedis(mr.Addr()), cfg, log, reg, reg)
	n := 0
	a.newCode = func() string { n++; return fmt.Sprintf("code%03d", n) }
	return a, store, mr, reg
}

func do(h http.Handler, method, path, body string) *httptest.ResponseRecorder {
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body)))
	return rec
}

func TestCreateAndRedirect(t *testing.T) {
	a, _, mr, _ := newTestApp(t)
	h := a.Handler()
	rec := do(h, "POST", "/links", `{"url": "https://go.dev/doc/"}`)
	want := `{"code":"code001","short_url":"https://lnk.test/code001","url":"https://go.dev/doc/"}` + "\n"
	if rec.Code != http.StatusCreated || rec.Body.String() != want {
		t.Fatalf("POST /links = %d %s", rec.Code, rec.Body)
	}
	for i := 0; i < 2; i++ { // the first redirect misses the cache, the second hits it
		rec = do(h, "GET", "/code001", "")
		if rec.Code != http.StatusFound || rec.Header().Get("Location") != "https://go.dev/doc/" {
			t.Fatalf("GET /code001 = %d %q", rec.Code, rec.Header().Get("Location"))
		}
	}
	for result, want := range map[string]float64{"miss": 1, "hit": 1} {
		if got := testutil.ToFloat64(a.cacheReqs.WithLabelValues(result)); got != want {
			t.Errorf("cache %s = %v, want %v", result, got, want)
		}
	}
	if ttl := mr.TTL("link:code001"); ttl != time.Hour {
		t.Errorf("cache TTL = %v, want 1h", ttl)
	}
}

func TestBadRequests(t *testing.T) {
	a, _, _, _ := newTestApp(t)
	h := a.Handler()
	do(h, "POST", "/links", `{"url": "https://example.com", "code": "docs"}`)
	for _, tc := range []struct {
		method, path, body string
		want               int
	}{
		{"POST", "/links", `not json`, 400},
		{"POST", "/links", `{"url": "ftp://example.com/file"}`, 400},
		{"POST", "/links", `{"url": "/relative/path"}`, 400},
		{"POST", "/links", `{"url": "https://example.com", "code": "a b"}`, 400},
		{"POST", "/links", `{"url": "https://example.org", "code": "docs"}`, 409},
		{"GET", "/nope", "", 404},
		{"GET", "/x", "", 404}, // too short to be a code: rejected before any lookup
		{"DELETE", "/links", "", 405},
	} {
		if rec := do(h, tc.method, tc.path, tc.body); rec.Code != tc.want {
			t.Errorf("%s %s %s = %d, want %d", tc.method, tc.path, tc.body, rec.Code, tc.want)
		}
	}
}

func TestRedisDownFallsBackToDatabase(t *testing.T) {
	a, store, mr, _ := newTestApp(t)
	h := a.Handler()
	store.links["docs"] = "https://go.dev/doc/"
	mr.Close()
	if rec := do(h, "GET", "/docs", ""); rec.Code != http.StatusFound {
		t.Fatalf("redirect without Redis = %d, want 302", rec.Code)
	}
	if got := testutil.ToFloat64(a.cacheReqs.WithLabelValues("error")); got != 1 {
		t.Errorf("cache errors = %v, want 1", got)
	}
	if rec := do(h, "GET", "/readyz", ""); rec.Code != http.StatusOK {
		t.Errorf("readyz without Redis = %d, want 200 (the cache is optional)", rec.Code)
	}
}

func TestReadiness(t *testing.T) {
	a, store, _, _ := newTestApp(t)
	h := a.Handler()
	store.down = true
	if rec := do(h, "GET", "/readyz", ""); rec.Code != http.StatusServiceUnavailable {
		t.Errorf("readyz without the database = %d, want 503", rec.Code)
	}
	store.down = false
	a.draining.Store(true)
	if rec := do(h, "GET", "/readyz", ""); rec.Code != http.StatusServiceUnavailable {
		t.Errorf("readyz while draining = %d, want 503", rec.Code)
	}
}

func TestMetricsUseRouteTemplates(t *testing.T) {
	a, store, _, reg := newTestApp(t)
	h := a.Handler()
	store.links["abc"] = "https://example.com"
	do(h, "GET", "/abc", "")
	do(h, "GET", "/zzz", "")
	do(h, "GET", "/a/b/c", "")
	want := `
# HELP http_requests_total HTTP requests by route and status code.
# TYPE http_requests_total counter
http_requests_total{code="302",route="/{code}"} 1
http_requests_total{code="404",route="/{code}"} 1
http_requests_total{code="404",route="unmatched"} 1
`
	if err := testutil.GatherAndCompare(reg, strings.NewReader(want), "http_requests_total"); err != nil {
		t.Error(err)
	}
}
EOF
cat > integration_test.go <<'EOF'
//go:build integration

package main

import (
	"context"
	"io"
	"log/slog"
	"os"
	"testing"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/prometheus/client_golang/prometheus"
)

// Run with real servers: DATABASE_URL=... REDIS_ADDR=... go test -tags integration ./...
func TestWithPostgresAndRedis(t *testing.T) {
	dsn, addr := os.Getenv("DATABASE_URL"), os.Getenv("REDIS_ADDR")
	if dsn == "" || addr == "" {
		t.Skip("DATABASE_URL and REDIS_ADDR are not set")
	}
	ctx := context.Background()
	db, err := pgxpool.New(ctx, dsn)
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()
	if err := migrate(ctx, db); err != nil {
		t.Fatal(err)
	}
	db.Exec(ctx, `DELETE FROM links WHERE code LIKE 'it-%'`)
	rdb := newRedis(addr)
	defer rdb.Close()
	rdb.Del(ctx, "link:it-docs")

	reg := prometheus.NewRegistry()
	cfg := config{BaseURL: "https://lnk.test", CacheTTL: time.Minute}
	h := newApp(pgStore{db}, rdb, cfg, slog.New(slog.NewJSONHandler(io.Discard, nil)), reg, reg).Handler()

	if rec := do(h, "POST", "/links", `{"url": "https://go.dev/doc/", "code": "it-docs"}`); rec.Code != 201 {
		t.Fatalf("create = %d %s", rec.Code, rec.Body)
	}
	if rec := do(h, "POST", "/links", `{"url": "https://example.com", "code": "it-docs"}`); rec.Code != 409 {
		t.Errorf("duplicate = %d, want 409 from the primary key", rec.Code)
	}
	if rec := do(h, "GET", "/it-docs", ""); rec.Code != 302 {
		t.Fatalf("redirect = %d", rec.Code)
	}
	if ttl := rdb.TTL(ctx, "link:it-docs").Val(); ttl <= 0 || ttl > time.Minute {
		t.Errorf("cached TTL = %v", ttl)
	}
	if rec := do(h, "GET", "/readyz", ""); rec.Code != 200 {
		t.Errorf("readyz = %d %s", rec.Code, rec.Body)
	}
}
EOF
cat > Makefile <<'MK'
VERSION ?= $(shell git describe --tags --always --dirty)
LDFLAGS := -s -w -X main.version=$(VERSION)

.PHONY: ci lint test integration vuln build scan

ci: lint test integration vuln build scan

lint:
	@test -z "$(gofmt -l .)" || { echo "gofmt needed:"; gofmt -l .; exit 1; }
	go vet ./...

test:
	go test -race ./...

integration:
	go test -race -tags integration -run WithPostgres ./...

vuln:
	govulncheck ./...

build:
	CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o dist/linkly .
	@echo "built dist/linkly $(VERSION)"

scan:
	trivy fs -q --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 .
MK
cat > Dockerfile <<'X'
# syntax=docker/dockerfile:1
FROM golang:1.27.3 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY *.go ./
ARG VERSION=dev
RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o /out/linkly .

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/linkly /linkly
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/linkly"]
X
printf '# Kubernetes uses the chart probes; distroless has no shell for a HEALTHCHECK.\nDS-0026\n' > .trivyignore
printf '/dist/\n' > .gitignore
go mod init github.com/acme/linkly >/dev/null 2>&1 && go mod tidy 2>/dev/null
git init -q && git add . && git commit -qm "linkly 1.4.0" && git tag v1.4.0
export DATABASE_URL="postgres:///linkly?host=/home/learner/pgrun" REDIS_ADDR=127.0.0.1:6379
make ci 2>&1 | sed -E 's/\t[0-9.]+s$//'
echo "make ci exit code: ${PIPESTATUS[0]}"
echo "== a badly formatted change"
sed -i 's/^func quiet(route string) bool {$/func quiet(route string)   bool {/' app.go
make lint; echo "make lint exit code: $?"
go vet ./...
go test -race ./...
ok  	github.com/acme/linkly
go test -race -tags integration -run WithPostgres ./...
ok  	github.com/acme/linkly
govulncheck ./...
No vulnerabilities found.
CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=v1.4.0" -o dist/linkly .
built dist/linkly v1.4.0
trivy fs -q --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 .

Report Summary

┌────────────┬────────────┬─────────────────┬─────────┬───────────────────┐
│   Target   │    Type    │ Vulnerabilities │ Secrets │ Misconfigurations │
├────────────┼────────────┼─────────────────┼─────────┼───────────────────┤
│ go.mod     │   gomod    │        0        │    -    │         -         │
├────────────┼────────────┼─────────────────┼─────────┼───────────────────┤
│ Dockerfile │ dockerfile │        -        │    -    │         0         │
└────────────┴────────────┴─────────────────┴─────────┴───────────────────┘
Legend:
- '-': Not scanned
- '0': Clean (no security findings detected)

make ci exit code: 0
== a badly formatted change
gofmt needed:
app.go
make: *** [Makefile:9: lint] Error 1
make lint exit code: 2

Every gate passed on the tagged commit: formatting and go vet, unit and integration tests under the race detector, govulncheck (no reachable known vulnerabilities in the code or its dependencies, per the sandbox's database snapshot), a static build stamped v1.4.0, and Trivy over go.mod (dependency CVEs), the Dockerfile (misconfigurations; DS-0026 is ignored with its reason) and every file (secrets). The formatting change then failed make lint with a non-zero exit code, which is all CI needs to block a merge.

govulncheck and Trivy answer different questions. govulncheck analyses which functions your code actually calls and reports a vulnerable module only when a vulnerable symbol is reachable; Trivy reports any dependency version with a known CVE. Run both: govulncheck tells you what is urgent, Trivy what to upgrade (and it also scans the final image's OS packages, which govulncheck can't).

The workflow

yaml
# .github/workflows/ci.yml
name: ci
on:
  pull_request:
  push:
    branches: [main]
    tags: ["v*"]

permissions:
  contents: read

concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

jobs:
  check:
    runs-on: ubuntu-24.04
    timeout-minutes: 15
    services:
      postgres:
        image: postgres:16
        env: {POSTGRES_USER: linkly, POSTGRES_PASSWORD: linkly, POSTGRES_DB: linkly}
        ports: ["5432:5432"]
        options: >-
          --health-cmd "pg_isready -U linkly" --health-interval 5s --health-timeout 5s --health-retries 10
      redis:
        image: redis:7
        ports: ["6379:6379"]
        options: --health-cmd "redis-cli ping" --health-interval 5s --health-timeout 5s --health-retries 10
    env:
      DATABASE_URL: postgres://linkly:linkly@localhost:5432/linkly?sslmode=disable
      REDIS_ADDR: localhost:6379
    steps:
      - uses: actions/checkout@v7
        with: {fetch-depth: 0}                # full history and tags for git describe
      - uses: actions/setup-go@v6
        with: {go-version-file: go.mod}
      - uses: acme/pipelines/actions/setup-tools@v3   # pinned govulncheck and Trivy (CI/CD: Reusable Workflows)
      - run: make lint test integration vuln build scan

  image:
    needs: check
    if: github.event_name == 'push'
    runs-on: ubuntu-24.04
    timeout-minutes: 20
    permissions:
      contents: read
      packages: write                         # push the image and chart to GHCR
    outputs:
      version: ${{ steps.version.outputs.version }}
      digest: ${{ steps.push.outputs.digest }}
    steps:
      - uses: actions/checkout@v7
        with: {fetch-depth: 0}
      - id: version
        run: echo "version=$(git describe --tags --always)" >> "$GITHUB_OUTPUT"
      - uses: docker/setup-buildx-action@v4
      - uses: docker/build-push-action@v7       # 1. build and load locally, don't push yet
        with:
          context: .
          load: true
          tags: linkly:candidate
          build-args: VERSION=${{ steps.version.outputs.version }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
      - uses: acme/pipelines/actions/setup-tools@v3
      - run: trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 linkly:candidate   # 2. gate
      - uses: docker/login-action@v4
        with: {registry: ghcr.io, username: "${{ github.actor }}", password: "${{ secrets.GITHUB_TOKEN }}"}
      - uses: docker/build-push-action@v7       # 3. push the same build from the cache
        id: push
        with:
          context: .
          push: true
          tags: ghcr.io/acme/linkly:${{ steps.version.outputs.version }}
          build-args: VERSION=${{ steps.version.outputs.version }}
          cache-from: type=gha
      - name: Package and push the chart (tags only)
        if: startsWith(github.ref, 'refs/tags/v')
        run: |
          v=${GITHUB_REF_NAME#v}
          helm package chart/linkly --version "$v" --app-version "$v"
          echo "${{ secrets.GITHUB_TOKEN }}" | helm registry login ghcr.io -u "${{ github.actor }}" --password-stdin
          helm push "linkly-$v.tgz" oci://ghcr.io/acme/charts

  bump-staging:
    needs: image
    runs-on: ubuntu-24.04
    timeout-minutes: 5
    steps:
      - uses: actions/create-github-app-token@v2   # short-lived token, scoped to the deploy repo
        id: token
        with:
          app-id: ${{ vars.DEPLOY_BOT_APP_ID }}
          private-key: ${{ secrets.DEPLOY_BOT_KEY }}
          repositories: linkly-deploy
      - uses: actions/checkout@v7
        with: {repository: acme/linkly-deploy, token: "${{ steps.token.outputs.token }}"}
      - run: |
          yq -i '.image.tag = "${{ needs.image.outputs.version }}" | .image.digest = "${{ needs.image.outputs.digest }}"' \
            apps/linkly/staging/values.yaml
          git config user.name "linkly-deploy-bot" && git config user.email "deploy-bot@users.noreply.github.com"
          git commit -am "staging: linkly ${{ needs.image.outputs.version }}" && git push

How it maps to the course's earlier lessons:

Decision Why Learn more
services: PostgreSQL and Redis with health checks the integration test runs against real servers, started before the steps Testing in CI
fetch-depth: 0 git describe needs tags and history; the default shallow clone has neither git describe
top-level permissions: contents: read, packages: write only in image least privilege per job Securing Workflows
build, scan, then push an image that fails the gate never reaches the registry Image Scanning
the digest goes to the deploy repo Argo CD deploys exactly the bytes that were scanned, even if someone re-pushes the tag Build → Scan → Push → Deploy
a GitHub App token for the deploy repo no long-lived personal token; the bot can only write linkly-deploy Secrets in Actions
CI never talks to the cluster the last job is a commit; Argo CD pulls (GitOps Delivery) What GitOps Is

Production is not bumped by CI. Promotion is a pull request in linkly-deploy that copies the staging version to production, reviewed by a human (Deploy, Roll Back & Tear Down).

Note: The uses: lines show major-version tags for readability. In your own repository, pin third-party actions to a full commit SHA (with the version in a comment) and let Dependabot or Renovate update them; the next lesson checks that rule automatically.

Test yourself

Why does the CI job run make lint test integration vuln build scan instead of listing the commands in YAML?

  1. GitHub Actions can't run go commands
  2. So developers can run exactly the same checks locally
  3. make is faster than bash
  4. YAML can't contain shell commands

govulncheck reports nothing, Trivy reports a CVE in a dependency. What is the most likely explanation?

  1. One of the databases is wrong
  2. The vulnerable function in that dependency is never called by linkly; Trivy matches versions, govulncheck checks reachable symbols
  3. govulncheck only scans the standard library
  4. Trivy can't read go.mod

What does the bump-staging job change?

  1. The cluster, through kubectl
  2. The image tag and digest in apps/linkly/staging/values.yaml in the deploy repository
  3. The production values file
  4. The chart version in the app repository