ggwhite/go-masker
ggwhite/go-masker has 131 GitHub stars and 35 forks. GitHot measured 0 stars in 24 hours. Last checked 2026-11-16 19:00 UTC. Last push 2026-11-09.
What you can do
- Dynamic tags, zero setup Pick how much to keep right in the tag: mid-4-4 for API keys, mobile-3-4 / id-0-4 for country-specific formats, tel-2-3-8 for international phone numbers, and first-N / last-N for anything else. No registration needed.
Measured star growth
- in 24h
- 0
- in 7 days
- Collecting history
- in 15 days
- Collecting history
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
About
Go library for masking sensitive data via struct tags — passwords, emails, IDs, credit cards, and more
SecurityREADME.md
OriginalMask passwords, emails, phones, IDs and cards in Go structs with a single struct tag.
Install · Quick Start · Features · Masker Types · Custom Masker · Sub-Modules · Docs
Go Masker is a simple and extensible library for masking sensitive data in Go structs. Use struct tags to control how fields are masked — passwords, emails, IDs, credit cards, and more.
Looking for v2? See the
release/v2branch.
Install
go get -u github.com/ggwhite/go-masker/v3
Requires Go 1.22+.
Quick Start
package main
import (
"fmt"
masker "github.com/ggwhite/go-masker/v3"
)
type User struct {
Name string `mask:"name"`
Email string `mask:"email"`
Password string `mask:"password"`
Mobile string `mask:"mobile"`
}
func main() {
u := &User{
Name: "John Doe",
Email: "[email protected]",
Password: "secret",
Mobile: "0987654321",
}
// Option 1: Get a masked copy of the struct
m := masker.NewMaskerMarshaler()
masked, err := m.Struct(u)
if err != nil {
panic(err)
}
fmt.Println(masked) // &{J**n D**e joh****@gmail.com ************** 0987***321}
// Option 2: Get a masked string directly (great for logging)
fmt.Println(m.Format(u)) // &{J**n D**e joh****@gmail.com ************** 0987***321}
}
You can also use the package-level default instance:
masked, err := masker.DefaultMaskerMarshaler.Struct(u)
Features
Dynamic tags, zero setupPick how much to keep right in the tag: |
![]() |
Plug in your own maskerAnything with a |
![]() |
Nested structs, slices and maps
|
![]() |
Sensitive[T]: safe by defaultWrap a value in |
![]() |
Run any of them yourself: go run ./examples/demo or go run ./examples/tour tags|custom|nested|sensitive.
Sensitive[T] — Type-Safe Masking
Sensitive[T] wraps a value so that all automatic output (fmt, JSON, slog) is masked. You must call .Reveal() to get the original value — leaking data requires an explicit opt-in.
phone := masker.NewPhone("0987654321")
fmt.Println(phone) // 0987***321
fmt.Println(phone.Reveal()) // 0987654321
b, _ := json.Marshal(phone) // "0987***321"
Built-in constructors: NewPhone, NewEmail, NewPassword, NewID, NewCredit, NewName, NewAddress, NewTel, NewURL.
Redact Mode
For compliance scenarios where partial masking is not enough:
phone := masker.NewPhone("0987654321", masker.WithRedact())
fmt.Println(phone) // [REDACTED]
fmt.Println(phone.Reveal()) // 0987654321
// Custom redact text
phone2 := masker.NewPhone("0987654321", masker.WithRedactText("***"))
fmt.Println(phone2) // ***
Database Integration
Sensitive[T] implements sql.Scanner and driver.Valuer, so it works directly with GORM and other ORMs:
type Player struct {
Phone masker.Sensitive[string] `gorm:"column:phone"`
}
// db.Find(&player) → auto scan + bind mask
// fmt.Println(player.Phone) → 0987***321 (masked)
// player.Phone.Reveal() → original value
Value()returns the original value (DB stores plaintext)Scan(nil)sets to zero value without panic
Format — Log-Friendly Output
Format() returns a deterministic masked string without allocating a new struct — ideal for logging and debugging:
m := masker.NewMaskerMarshaler()
type Foo struct {
Name string `mask:"name"`
Email string `mask:"email"`
Self *Foo `mask:"struct"`
}
foo := &Foo{
Name: "John Doe",
Email: "[email protected]",
Self: &Foo{Name: "Jane Doe", Email: "[email protected]"},
}
fmt.Println(m.Format(foo))
// &{J**n D**e joh****@gmail.com &{J**e D**e jan****@gmail.com <nil>}}
- Pointer-to-struct fields are expanded as
&{...}(no memory address) nilpointers display as<nil>- Output is deterministic — same input always produces the same string
Masker Types
| Tag | Description | Example Input | Example Output |
|---|---|---|---|
none |
No masking, return as-is | foo |
foo |
password |
Always returns 14 asterisks | secret |
************** |
name |
Masks middle characters | John Doe |
J**n D**e |
addr |
Keeps first 6 chars, rest → ****** |
台北市內湖區內湖路一段737巷1號 |
台北市內湖區****** |
email |
Keeps first 3 chars and domain | [email protected] |
joh****@gmail.com |
mobile |
Masks 3 digits from 4th position | 0987654321 |
0987***321 |
mobile-F-E |
Keep first F, last E, mask middle | 09012345678 (mobile-3-4) |
090****5678 |
tel |
Formats and masks last 4 digits | 0227993078 |
(02)2799-**** |
id |
Masks digits 7–10 | A123456789 |
A12345**** |
id-F-E |
Keep first F, last E, mask middle | 123456789 (id-0-4) |
*****6789 |
mid-F-E |
Generic: keep F front, E end | sk-abc123xyz (mid-4-4) |
sk-a****3xyz |
credit |
Masks digits 7–12 | 4111111111111111 |
411111******1111 |
url |
Masks URL password | http://user:pass@host |
http://user:xxxxx@host |
all |
Replaces every character | secret |
****** |
abuse |
Masks abusive words via trie | bad word |
*** word |
first-N |
Masks the first N chars | ABC123 (first-3) |
***123 |
last-N |
Masks the last N chars | secret99 (last-4) |
secr**** |
tel-R-N |
Region + number, last 4 masked | 0227993078 (tel-2-8) |
02-2799-**** |
struct |
Recursively masks nested struct | — | — |
mapstruct |
Recursively masks map values | — | — |
Dynamic Mask Tags
Use first-N and last-N to mask a specific number of characters from the start or end:
type Token struct {
Code string `mask:"first-3"` // masks first 3 chars
Suffix string `mask:"last-4"` // masks last 4 chars
}
m := masker.NewMaskerMarshaler()
masked, _ := m.Struct(&Token{Code: "ABC123", Suffix: "secret99"})
// Code: "***123"
// Suffix: "secr****"
Use tel-<regionLen>-<numberLen>[-sep] (optionally prefixed with
<intlLen>-) when the fixed tel format doesn't fit — e.g. area codes
longer than 2 digits, or numbers that include a country code:
type Contact struct {
TWPhone string `mask:"tel-2-8"` // "0227993078" -> "02-2799-****"
CNPhone string `mask:"tel-3-8-space"` // "75588888888" -> "755 8888 ****"
IntlPhone string `mask:"tel-2-3-8"` // "8675588888888" -> "+86-755-8888-****"
}
The input must already be normalized to the exact digit count implied by
the tag (no leading trunk 0, no formatting other than optional
+/-/space/() which are stripped). See
docs/masker-types.md for the
full grammar.
Use mid-<keepFront>-<keepEnd> to keep the first F and last E
characters while masking everything in between. mobile- and id- are
semantic aliases — same behavior, but the tag name documents the field's
data type:
type User struct {
PhoneJP string `mask:"mobile-3-4"` // "09012345678" -> "090****5678"
PhoneUS string `mask:"mobile-3-4"` // "2025551234" -> "202***1234"
SSN string `mask:"id-0-4"` // "123456789" -> "*****6789"
MyNumber string `mask:"id-4-0"` // "123456789012" -> "1234********"
APIKey string `mask:"mid-4-4"` // "sk-abc123xyz" -> "sk-a****3xyz"
}
If keepFront + keepEnd >= len(value), the value is returned unchanged
(nothing to mask). See
docs/masker-types.md for
details.
Masking Slices
String slices are also supported:
type Foo struct {
Tags []string `mask:"name"`
}
Masking Nested Structs
type Address struct {
Street string `mask:"addr"`
}
type User struct {
Name string `mask:"name"`
Address Address `mask:"struct"`
}
Masking Maps
Use mask:"mapstruct" on map fields to recursively mask map values:
- Recurses through
map,struct,ptr, andslicecombinations (including nested map and pointer-to-slice forms) - Map keys are never masked; only values are processed
nilvalues are preserved (nilmap,nilpointer,nilslice)- Leaf values without mask tags are kept as-is
type Item struct {
ID string `mask:"id"`
}
type Payload struct {
Items map[int]Item `mask:"mapstruct"`
Ptrs map[int]*Item `mask:"mapstruct"`
SliceItems map[int][]Item `mask:"mapstruct"`
PtrSlices map[int]*[]Item `mask:"mapstruct"`
Nested map[int]map[string]map[int][]Item `mask:"mapstruct"`
}
m := masker.NewMaskerMarshaler()
masked, _ := m.Struct(Payload{
Items: map[int]Item{1: {ID: "A123456789"}},
Ptrs: map[int]*Item{1: {ID: "A123456789"}, 2: nil},
SliceItems: map[int][]Item{1: {{ID: "A123456789"}, {ID: "B223456789"}}},
PtrSlices: func() map[int]*[]Item {
x := []Item{{ID: "A123456789"}, {ID: "B223456789"}}
return map[int]*[]Item{1: &x, 2: nil}
}(),
Nested: map[int]map[string]map[int][]Item{
1: {
"group": {
10: {{ID: "C323456789"}},
},
},
},
})
// Items[1].ID => A12345****
// Ptrs[1].ID => A12345****
// Ptrs[2] => nil
// SliceItems[1][0].ID => A12345****
// PtrSlices[1][1].ID => B22345****
// PtrSlices[2] => nil
// Nested[1]["group"][10][0].ID => C32345****
Custom Mask Character
By default, * is used as the mask character. Use WithMaskChar to change it:
m := masker.NewMaskerMarshaler(masker.WithMaskChar('#'))
masked, _ := m.Struct(u)
// Name "John" -> "J##n"
Abuse Masker
The abuse masker uses a trie for efficient word matching and replacement.
Basic Usage
abuseMasker := masker.NewAbuseMaskerWithWords("*", []string{"bad", "terrible", "awful"})
masked := abuseMasker.Mask("This is a bad and terrible situation")
// "This is a *** and ******** situation"
Load Words from File
loader := masker.NewAbuseWordLoader()
words, err := loader.LoadFromFile("abuse_words.txt")
if err != nil {
log.Fatal(err)
}
abuseMasker := masker.NewAbuseMaskerWithWords("*", words)
Use with Struct Tags
type Post struct {
Title string `mask:"name"`
Content string `mask:"abuse"`
}
m := masker.NewMaskerMarshaler()
m.Register(masker.TypeAbuse, masker.NewAbuseMaskerWithWords("*", []string{"bad"}))
masked, _ := m.Struct(&Post{Title: "Hello", Content: "bad content"})
Custom Masker
Implement the Masker interface to create your own masker:
type Masker interface {
Mask(value string) string
}
Example:
type SSNMasker struct{}
func (m *SSNMasker) Mask(value string) string {
if len(value) != 9 {
return value
}
return "***-**-" + value[7:]
}
m := masker.NewMaskerMarshaler()
m.Register("ssn", &SSNMasker{})
type Person struct {
SSN string `mask:"ssn"`
}
Sub-Modules
Optional sub-modules for integrating masking into your logging and HTTP stack. Each is a separate go get — they don't add dependencies to the core module.
zapfield — Zap Logger Integration
go get github.com/ggwhite/go-masker/zapfield
import "github.com/ggwhite/go-masker/zapfield"
logger.Info("user login",
zapfield.Phone("phone", "0987654321"), // 0987***321
zapfield.Email("email", "[email protected]"), // joh****@g.com
)
WrapCore intercepts log fields by keyword, with per-rule masker type support:
core = zapfield.WrapCore(core, zapfield.InterceptRules{
Rules: []zapfield.Rule{
{Keywords: []string{"phone", "mobile"}, MaskerType: masker.TypeMobile},
{Keywords: []string{"password", "secret"}, MaskerType: masker.TypePassword},
},
})
slogfield — slog Integration
go get github.com/ggwhite/go-masker/slogfield
import "github.com/ggwhite/go-masker/slogfield"
slog.Info("user login",
slogfield.Phone("phone", "0987654321"), // 0987***321
slogfield.Email("email", "[email protected]"), // joh****@g.com
)
ginmasker — Gin Middleware
go get github.com/ggwhite/go-masker/ginmasker
Access log middleware that automatically masks sensitive fields in request/response JSON body. Only affects log output — never modifies the actual request or response.
import "github.com/ggwhite/go-masker/ginmasker"
r := gin.New()
r.Use(ginmasker.Middleware(
ginmasker.WithLogger(logger),
ginmasker.WithKeywords("password", "token", "secret"),
ginmasker.WithQueryMask("api_key"),
ginmasker.WithHeaderMask("Authorization"),
))
Performance
Struct() caches type metadata on first call via sync.Map, so repeated calls on the same struct type skip reflection overhead. Benchmarks show ≥ 50% improvement on subsequent calls.
Format() avoids allocating a new struct entirely — it writes masked output directly to a strings.Builder, making it the better choice for log-only use cases.
Migration from v2
The module path changes from github.com/ggwhite/go-masker/v2 to github.com/ggwhite/go-masker/v3. Key API changes:
| v2 | v3 |
|---|---|
Masker.Marshal(maskChar, value) |
Masker.Mask(value) |
MaskerTypeMobile |
TypeMobile |
m.SetMasker("#") |
NewMaskerMarshaler(WithMaskChar('#')) |
NewAbuseMaskerWithWords(words) |
NewAbuseMaskerWithWords("*", words) |
Contributors
Thanks to all the people who already contributed!


![An Order struct with a *Person tagged struct, a []string tagged email and a map[string]Item tagged mapstruct; go run ./examples/tour nested prints each field fully masked](https://raw.githubusercontent.com/ggwhite/go-masker/master/assets/nested.webp)
![go run ./examples/tour sensitive: NewPhone(0987654321) prints 0987***321 with fmt and JSON, Reveal() returns 0987654321, and WithRedact() prints [REDACTED]](https://raw.githubusercontent.com/ggwhite/go-masker/master/assets/sensitive.webp)