Skip to content

Base64 Encode / Decode — Go source

Encode text to Base64 or decode it back. UTF-8 safe, runs entirely in your browser, with a shareable link to your exact input.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package base64 is the Go twin of CosmoDev's src/lib/base64.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 base64_test.go share
// vectors with src/lib/base64.test.ts so the two implementations are held to
// the same contract.
//
// The twin mirrors the TS lib exactly: B64encode treats the input as UTF-8
// bytes and applies standard (RFC 4648) base64; B64decode strips all
// whitespace (matching JS /\s+/g via unicode.IsSpace), base64-decodes, and
// returns the UTF-8 string. Decode returns an error on invalid input instead
// of throwing.
package base64

import (
	b64 "encoding/base64"
	"strings"
	"unicode"
)

// B64encode encodes a string to standard base64 (with padding). It is the Go
// twin of b64encode() in src/lib/base64.ts and must agree with it on every
// shared vector. Encoding never fails: the input is treated as UTF-8 bytes,
// exactly like the TS lib's TextEncoder path.
func B64encode(s string) string {
	return b64.StdEncoding.EncodeToString([]byte(s))
}

// B64decode decodes a standard base64 string back to the original UTF-8 string.
// It is the Go twin of b64decode() in src/lib/base64.ts. All whitespace
// (unicode.IsSpace, matching JS \s) is stripped before decoding, mirroring the
// TS lib's b64.replace(/\s+/g, ''). Invalid input yields a non-nil error
// instead of the TS throw.
func B64decode(s string) (string, error) {
	data, err := b64.StdEncoding.DecodeString(stripWhitespace(s))
	if err != nil {
		return "", err
	}
	return string(data), nil
}

// stripWhitespace removes every whitespace rune from s. Mirrors the TS lib's
// b64.replace(/\s+/g, ''); unicode.IsSpace covers ASCII \t\n\v\f\r\space plus
// Unicode spaces (NBSP, thin space, etc.), matching JS \s more closely than
// RE2's \s class, which omits \v and Unicode whitespace.
func stripWhitespace(s string) string {
	return strings.Map(func(r rune) rune {
		if unicode.IsSpace(r) {
			return -1 // drop the rune
		}
		return r
	}, s)
}

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 →