Skip to content

A lightweight Go library for safely updating struct fields using dot-notation paths. It is fast, dependency-free, supports nested structs and JSON tags, and is optimized for partial updates in APIs.

License

Notifications You must be signed in to change notification settings

g3deon/fieldmask

Repository files navigation

Go FieldMask

Actions Status Go Reference Go Version License: MIT

A lightweight Go library for safely updating struct fields using dot-notation paths. It is fast, dependency-free, supports nested structs and JSON tags, and is optimized for partial updates in APIs.

Installation

  go get go.g3deon.com/fieldmask

Usage

Basic Example

package main

import (
  "fmt"
  "go.g3deon.com/fieldmask"
)

type Profile struct {
  Age int `json:"age"`
}

type User struct {
  Name    string  `json:"name"`
  Email   string  `json:"email"`
  Profile Profile `json:"profile"`
}

func main() {
  user := &User{
    Name:  "John",
    Email: "john@example.com",
    Profile: Profile{
      Age: 30,
    },
  }

  mask := fieldmask.New("name", "profile.age")

  if err := mask.Apply(user); err != nil {
    panic(err)
  }

  fmt.Printf("%+v\n", user)
  // Output: {Name:John Email: Profile:{Age:30}}
}

Getting Paths

Use GetPaths() instead of accessing the Paths field directly.

mask := fieldmask.New("name", "profile.age")

paths := mask.GetPaths()
fmt.Println(paths)
// Output: FieldMask{Paths: name, profile.age}

Removing Paths

Remove one or multiple paths using RemovePaths().

mask := fieldmask.New("name", "profile.age")

mask.RemovePaths("name", "unknown")

fmt.Println(mask)
// Output: FieldMask{Paths: profile.age}

Normalizing Paths

The New function automatically normalizes paths by removing duplicates and empty values. To manually normalize, use Normalize().

mask := fieldmask.FieldMask{
  Paths: []string{"name", "name", "", "profile.age"},
}

mask.Normalize()

fmt.Println(mask)
// Output: FieldMask{Paths: name, profile.age}

License

MIT © 2025 G3deon, Inc.

About

A lightweight Go library for safely updating struct fields using dot-notation paths. It is fast, dependency-free, supports nested structs and JSON tags, and is optimized for partial updates in APIs.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages