package web
import (
"bytes"
"html/template"
"net/http"
)
func Render(w http.ResponseWriter, t *template.Template, name string, data any) error {
var buf bytes.Buffer
if err := t.ExecuteTemplate(&buf, name, data); err != nil {
return err
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, err := w.Write(buf.Bytes())
return err
}
Even in API-heavy systems, I occasionally render HTML emails or a lightweight admin page. I always use html/template (not text/template) so content is escaped by default, which prevents accidental XSS when variables contain user input. I also keep templates parsed at startup so errors surface during boot, not under traffic. The helper below renders to a bytes.Buffer first, then writes a complete response, which avoids partial output if execution fails. Another operational detail: templates should be treated like code and tested with representative data; a missing field can cause a runtime error if you’re not careful. For emails, I render both a plain-text and HTML variant and keep subject lines separate. This is a safe, boring approach that avoids the “string concatenation HTML” trap.
Related snips
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
#!/usr/bin/env bash
set -euo pipefail
export VAULT_ADDR="https://vault.internal:8200"
export VAULT_TOKEN="${VAULT_TOKEN:?missing VAULT_TOKEN}"
Secrets management with environment isolation and Vault
import { randomBytes, createHash } from "crypto";
import jwt from "jsonwebtoken";
import { RefreshTokenStore } from "./store";
const ACCESS_SECRET = process.env.ACCESS_SECRET!;
const ACCESS_TTL = "15m";
JWT access + refresh token rotation (conceptual)
Share this code
Here's the card — post it anywhere.