go
41 lines · 6 steps
Masking card numbers in Go
Two functions that strip non-digits and replace all but the last four digits with asterisks — one for a single value, one for free text.
Explained by
highlit
1package payment
2
3import (
4 "regexp"
5 "strings"
6)
7
8var cardPattern = regexp.MustCompile(`\b(?:\d[ -]?){12,15}\d\b`)
9
10func MaskCardNumber(card string) string {
11 var digits strings.Builder
12 for _, r := range card {
13 if r >= '0' && r <= '9' {
14 digits.WriteRune(r)
15 }
16 }
17
18 clean := digits.String()
19 if len(clean) < 4 {
20 return card
21 }
22
23 last4 := clean[len(clean)-4:]
24 return strings.Repeat("*", len(clean)-4) + last4
25}
26
27func MaskCardsInText(text string) string {
28 return cardPattern.ReplaceAllStringFunc(text, func(match string) string {
29 var digits strings.Builder
30 for _, r := range match {
31 if r >= '0' && r <= '9' {
32 digits.WriteRune(r)
33 }
34 }
35 clean := digits.String()
36 if len(clean) < 13 {
37 return match
38 }
39 return strings.Repeat("*", len(clean)-4) + clean[len(clean)-4:]
40 })
41}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Normalizing input by extracting only digits lets masking logic ignore spaces and dashes entirely.
- 2ReplaceAllStringFunc lets you run custom per-match logic instead of a fixed replacement string.
- 3Guard clauses that return the original input keep short or non-card values untouched.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/masking-card-numbers-in-go-explained-go-f2c2/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.