Defang / Refang — Go source
Make URLs, IPs, and emails safe to paste by defanging indicators (https:// → hxxps[://], . → [.], @ → [@]) - and reverse refanged text back to its original form. Runs entirely in your browser, with a shareable link to your exact input and mode.
This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package defangrefang is the Go twin of CosmoDev's src/lib/defang.ts (dual
// source: the web lib is TypeScript, the CLI lib is Go — kept in lock-step).
// Pure + deterministic, never panics. The table-driven tests in
// defang-refang_test.go share vectors with src/lib/defang.test.ts so the two
// implementations are held to the same contract.
//
// Defang makes URLs, IPs, and emails safe to paste by replacing the https/http
// schemes with hxxps[://]/hxxp[://] markers and bracketing every dot as [.] and
// every at-sign as [@] — the standard threat-intel defanging convention. Refang
// is its exact inverse. Scheme replacements run before dot/at bracketing so the
// dots and colon inside the resulting [://] marker are not themselves
// re-bracketed. The port mirrors the TS lib's chained-replacement algorithm one
// for one.
package defangrefang
import "strings"
// Defang makes URLs, IPs, and emails no longer clickable or auto-linked. It is
// the Go twin of defang() in src/lib/defang.ts and must agree with it on every
// shared vector.
//
// Scheme replacements run FIRST so the dots and colon inside the resulting
// [://] marker are not themselves re-bracketed (which would corrupt the scheme
// marker). Note that EVERY dot is bracketed, not just the domain separator.
// Empty input returns empty; text with no indicators passes through unchanged.
func Defang(input string) string {
out := strings.ReplaceAll(input, "https://", "hxxps[://]")
out = strings.ReplaceAll(out, "http://", "hxxp[://]")
out = strings.ReplaceAll(out, ".", "[.]")
out = strings.ReplaceAll(out, "@", "[@]")
return out
}
// Refang reverses defanging — restoring hxxps[://]/hxxp[://] to real schemes
// and unbracketing [.]/[@]. It is the Go twin of refang() in src/lib/defang.ts,
// the exact inverse of Defang: for typical URLs, IPs, emails, and plain text,
// Refang(Defang(x)) == x.
//
// Scheme markers are restored before [.]/[@] are unbracketed, so a marker like
// hxxps[://] reassembles into https:// rather than being split by an earlier
// dot/at substitution. Empty input returns empty.
func Refang(input string) string {
out := strings.ReplaceAll(input, "hxxps[://]", "https://")
out = strings.ReplaceAll(out, "hxxp[://]", "http://")
out = strings.ReplaceAll(out, "[.]", ".")
out = strings.ReplaceAll(out, "[@]", "@")
return out
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →