Skip to content

Go libraries, Open source

xMapper

Struct validation and mapping library for Go

A Go library that validates data and maps it from one struct to another, transforming fields along the way.

Go code from the xMapper README typed into an editor: a Source struct whose Greeting field chains the toUpperCase, addExclamation and repeatTwice transformers, mapped to a Destination with xmapper.MapStructs to give "HELLO! HELLO!", and the go get command below.
Chained transformers, from the README

Stack

  • Go
  • Open source
  • Library
Status
Open source
Type
Go libraries
Source
GitHub

The problem

Copying fields from one Go struct to another by hand is repetitive and easy to get wrong.

What it does

xMapper automates mapping between Go structs. It validates the data and transforms values dynamically as they move from source to destination. Its behavior is customizable.

How it's built

A Go library using Go modules (Go 1.11+), open source on GitHub.

Key features

  • Struct-to-struct mapping
  • Validation rules and transformers declared in struct tags, for example validators:"email" and transformers:"trim,lowercase"
  • Validate a single struct without mapping, with a typed validation error (xmapper.ErrValidation)
  • Dynamic transforms as data flows from source to destination
  • Customizable to your needs

Install and usage

Install

go get github.com/dev3mike/go-xmapper
Validate a single struct without mapping

go

type User struct {
    Email string `json:"email" validators:"email" transformers:"trim,lowercase"`
}

user := User{Email: "[email protected]"}

// Call ValidateStruct to check validation.
err := xmapper.ValidateStruct(&user)

// Check error type for validation errors
if errors.Is(err, xmapper.ErrValidation) {
    // Return bad request or ...
}
  • xMapper README example: a ProfileDto with an isEmail validator and a toUpperCase transformer, a JSON string mapped into it with xmapper.MapJsonStruct, and errors.Is(err, xmapper.ErrValidation) to detect validation errors.
    Validate and map JSON into a struct

Contact

Want something like this built?