package deps
import (
"crypto/tls"
"crypto/x509"
"net/http"
"os"
)
func NewMTLSClient(caPath, certPath, keyPath, serverName string) (*http.Client, error) {
caPEM, err := os.ReadFile(caPath)
if err != nil {
return nil, err
}
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(caPEM)
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, err
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
RootCAs: pool,
Certificates: []tls.Certificate{cert},
ServerName: serverName,
},
}
return &http.Client{Transport: tr}, nil
}
For internal service-to-service calls, mutual TLS is a pragmatic way to get strong identity without bespoke auth headers. The main pitfalls are certificate rotation and trust configuration. I build a x509.CertPool from a dedicated internal CA, load a client certificate/key pair, and set MinVersion to TLS1.2 (or newer) to avoid legacy negotiation. The tls.Config also sets ServerName so hostname verification happens correctly; skipping verification is a common anti-pattern. In production I pair this with short-lived certificates and automatic reload, but even the static version shown here is a solid baseline. When something breaks, the errors are actionable: either trust is wrong, cert is expired, or the peer identity doesn’t match.
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.