Skip to content

Hreflang Tag Generator — Go source

Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.

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

// Package hreflangtaggenerator is the Go twin of CosmoDev's src/lib/hreflang.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
// hreflang-tag-generator_test.go share vectors with src/lib/hreflang.test.ts
// so the two implementations are held to the same contract.
//
// Behaviour mirrors the TS lib exactly: pure locale-list validation +
// alternate-link emission. No DOM — rows in, an HTML <link> block and an XML
// sitemap <xhtml:link> block out. Invalid input collects every error
// (row-located) and emits empty blocks; valid input normalizes locales,
// preserves row order, and appends x-default last.
package hreflangtaggenerator

import (
	"fmt"
	"regexp"
	"strings"
)

// HreflangRow is one locale/URL pair. Mirrors the TS HreflangRow interface.
type HreflangRow struct {
	Locale string
	URL    string
}

// HreflangInput is the field set for BuildHreflang. The zero value
// (HreflangInput{}) matches the TS shape with rows omitted entirely: no rows,
// no x-default URL.
type HreflangInput struct {
	Rows        []HreflangRow
	XDefaultURL string
}

// HreflangResult carries the diagnostics and both emitted flavors. On failure
// Ok is false, Errors lists every row-located problem, and Normalized/HTML/
// Sitemap are empty — exactly like the TS result.
type HreflangResult struct {
	Ok         bool
	Errors     []string
	Normalized []HreflangRow
	HTML       string
	Sitemap    string
}

var (
	// ll (ISO-639-1 language) — two ASCII letters.
	singleLocale = regexp.MustCompile(`^[a-zA-Z]{2}$`)
	// ll-CC — two-letter language, two-letter region (ISO-3166).
	regionLocale = regexp.MustCompile(`^([a-zA-Z]{2})-([a-zA-Z]{2})$`)
	// http:// or https:// scheme prefix.
	validURLRe = regexp.MustCompile(`^https?://`)
)

// NormalizeLocale normalizes a locale tag to Google's hreflang grammar:
// ll (ISO-639-1, lowercase) or ll-CC (region uppercase, ISO-3166). Case and
// surrounding whitespace are corrected (en-us → en-US); anything else is
// invalid and returns nil. It is the Go twin of normalizeLocale() in
// src/lib/hreflang.ts — the nil return stands in for the TS null.
func NormalizeLocale(raw string) *string {
	t := strings.TrimSpace(raw)
	if singleLocale.MatchString(t) {
		out := strings.ToLower(t)
		return &out
	}
	if m := regionLocale.FindStringSubmatch(t); m != nil {
		out := strings.ToLower(m[1]) + "-" + strings.ToUpper(m[2])
		return &out
	}
	return nil
}

// validURL trims raw and returns it when it starts with http:// or https://,
// otherwise "". Mirrors the TS validUrl() helper (empty string ≈ null).
func validURL(raw string) string {
	t := strings.TrimSpace(raw)
	if validURLRe.MatchString(t) {
		return t
	}
	return ""
}

// BuildHreflang validates a locale/URL table and emits both hreflang flavors.
// It is the Go twin of buildHreflang() in src/lib/hreflang.ts and must agree
// with it on every shared vector: invalid input collects every error
// (row-located) and emits empty blocks; valid input normalizes locales,
// preserves row order, and appends x-default last.
func BuildHreflang(input HreflangInput) HreflangResult {
	var errors []string
	var normalized []HreflangRow
	seen := map[string]bool{}

	for i, row := range input.Rows {
		n := i + 1
		locale := NormalizeLocale(row.Locale)
		if locale == nil {
			errors = append(errors, fmt.Sprintf("Row %d: \"%s\" is not a valid locale — use ll or ll-CC (e.g. en, de-AT).", n, strings.TrimSpace(row.Locale)))
			continue
		}
		if seen[*locale] {
			errors = append(errors, fmt.Sprintf("Row %d: locale \"%s\" is already used.", n, *locale))
			continue
		}
		if strings.TrimSpace(row.URL) == "" {
			errors = append(errors, fmt.Sprintf("Row %d: URL is required.", n))
			continue
		}
		url := validURL(row.URL)
		if url == "" {
			errors = append(errors, fmt.Sprintf("Row %d: URL must start with http:// or https://.", n))
			continue
		}
		seen[*locale] = true
		normalized = append(normalized, HreflangRow{Locale: *locale, URL: url})
	}

	xDefault := ""
	if strings.TrimSpace(input.XDefaultURL) != "" {
		xDefault = validURL(input.XDefaultURL)
		if xDefault == "" {
			errors = append(errors, "x-default: URL must start with http:// or https://.")
		}
	}

	if len(errors) > 0 {
		return HreflangResult{Ok: false, Errors: errors, Normalized: nil, HTML: "", Sitemap: ""}
	}

	htmlLines := make([]string, 0, len(normalized)+1)
	sitemapLines := make([]string, 0, len(normalized)+1)
	for _, r := range normalized {
		htmlLines = append(htmlLines, fmt.Sprintf("<link rel=\"alternate\" href=\"%s\" hreflang=\"%s\" />", r.URL, r.Locale))
		sitemapLines = append(sitemapLines, fmt.Sprintf("    <xhtml:link rel=\"alternate\" hreflang=\"%s\" href=\"%s\"/>", r.Locale, r.URL))
	}
	if xDefault != "" {
		htmlLines = append(htmlLines, fmt.Sprintf("<link rel=\"alternate\" href=\"%s\" hreflang=\"x-default\" />", xDefault))
		sitemapLines = append(sitemapLines, fmt.Sprintf("    <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"%s\"/>", xDefault))
	}

	return HreflangResult{
		Ok:         true,
		Errors:     nil,
		Normalized: normalized,
		HTML:       strings.Join(htmlLines, "\n"),
		Sitemap:    strings.Join(sitemapLines, "\n"),
	}
}

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 →