Skip to content

Basic Auth Generator — Go source

Build HTTP Basic Access Authentication headers from a username and password, or decode an existing Authorization header back to its credentials. UTF-8 safe and fully client-side, with a shareable link.

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

// Package basicauth is the Go twin of CosmoDev's src/lib/basic-auth.ts (dual
// source: web lib is TypeScript, CLI lib is Go — kept in lock-step). Pure +
// deterministic, never panics. Table-driven tests share vectors with the TS suite.
package basicauth

import (
	"encoding/base64"
	"strings"
)

// Credentials holds a parsed username/password pair.
type Credentials struct {
	User string
	Pass string
}

// BuildHeader returns an HTTP Basic-Auth header value: "Basic " + base64(user:pass).
// Mirrors buildBasicAuth() in basic-auth.ts.
func BuildHeader(user, pass string) string {
	return "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass))
}

// ParseHeader parses a "Basic <token>" header back into credentials, returning
// ok=false if the header is malformed or the credentials have no colon separator.
func ParseHeader(header string) (Credentials, bool) {
	h := strings.TrimSpace(header)
	if len(h) < 6 || !strings.EqualFold(h[:6], "basic ") {
		return Credentials{}, false
	}
	token := strings.TrimSpace(h[6:])
	b, err := base64.StdEncoding.DecodeString(token)
	if err != nil {
		return Credentials{}, false
	}
	user, pass, found := strings.Cut(string(b), ":")
	if !found {
		return Credentials{}, false
	}
	return Credentials{User: user, Pass: pass}, true
}

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 →