All Projects → jmattheis → goverter

jmattheis / goverter

Licence: MIT License
Generate type-safe Go converters by simply defining an interface

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to goverter

Toml To Go
Translates TOML into a Go type in your browser instantly
Stars: ✭ 134 (+34%)
Mutual labels:  converter, generator, struct
Struct2ts
Generate Typescript classes/interfaces out of Go structs
Stars: ✭ 116 (+16%)
Mutual labels:  generator, struct
Faker
Go (Golang) Fake Data Generator for Struct
Stars: ✭ 1,698 (+1598%)
Mutual labels:  generator, struct
Jsontocodable
A generating tool from Raw JSON to Codable (Swift4) text written in Swift4.
Stars: ✭ 33 (-67%)
Mutual labels:  converter, generator
Laravel Code Generator
An intelligent code generator for Laravel framework that will save you time! This awesome tool will help you generate resources like views, controllers, routes, migrations, languages and/or form-requests! It is extremely flexible and customizable to cover many on the use cases. It is shipped with cross-browsers compatible template, along with a client-side validation to modernize your application.
Stars: ✭ 485 (+385%)
Mutual labels:  generator, code-generation
Go Envparser
a go generator based env to go-struct decoder.
Stars: ✭ 17 (-83%)
Mutual labels:  generator, struct
Glad
Multi-Language Vulkan/GL/GLES/EGL/GLX/WGL Loader-Generator based on the official specs.
Stars: ✭ 2,296 (+2196%)
Mutual labels:  generator, code-generation
Coolie
Coolie(苦力) helps you to create models (& their constructors) from a JSON file.
Stars: ✭ 508 (+408%)
Mutual labels:  generator, struct
Converter
database table to golang struct (table to struct) converter with cli and go lib support
Stars: ✭ 167 (+67%)
Mutual labels:  converter, struct
copygen
Go generator to copy values from type to type and fields from struct to struct (copier without reflection). Generate any code based on types.
Stars: ✭ 121 (+21%)
Mutual labels:  copy, code-generation
Swaggen
OpenAPI/Swagger 3.0 Parser and Swift code generator
Stars: ✭ 385 (+285%)
Mutual labels:  generator, code-generation
FigmaConvertXib
FigmaConvertXib is a tool for exporting design elements from figma.com and generating files to a projects iOS .xib / Android .xml
Stars: ✭ 111 (+11%)
Mutual labels:  converter, generator
Swiftcolorgen
A tool that generate code for Swift projects, designed to improve the maintainability of UIColors
Stars: ✭ 152 (+52%)
Mutual labels:  generator, code-generation
Net Core Docx Html To Pdf Converter
.NET Core library to create custom reports based on Word docx or HTML documents and convert to PDF
Stars: ✭ 133 (+33%)
Mutual labels:  converter, generator
fieldmask-utils
Protobuf Field Mask Go utils
Stars: ✭ 127 (+27%)
Mutual labels:  copy, struct
DataAnalyzer.app
✨🚀 DataAnalyzer.app - Convert JSON/CSV to Typed Data Interfaces - Automatically!
Stars: ✭ 23 (-77%)
Mutual labels:  generator, code-generation
wsdl-tsclient
📄 Generate typescript client from wsdl
Stars: ✭ 30 (-70%)
Mutual labels:  generator
docgen
The docs.json generator for discord.js and its related projects
Stars: ✭ 59 (-41%)
Mutual labels:  generator
filter
⏳ Provide filtering, sanitizing, and conversion of Golang data. 提供对Golang数据的过滤,净化,转换。
Stars: ✭ 53 (-47%)
Mutual labels:  converter
NFT Art Generator
No description or website provided.
Stars: ✭ 58 (-42%)
Mutual labels:  generator

goverter

a "type-safe Go converter" generator

Build Status codecov Go Report Card Go Reference latest release

goverter is a tool for creating type-safe converters. All you have to do is create an interface and execute goverter. The project is meant as alternative to jinzhu/copier that doesn't use reflection.

Features

  • Automatic conversion of builtin types (house example), this includes:
    • slices, maps, named types, primitive types, pointers
    • structs with same fields
  • Extend parts of the conversion with your own implementation: Docs
  • Optional return of an error: Docs
  • Awesome error messages: mismatch type test
  • No reflection in the generated code

Usage

  1. Create a go modules project if you haven't done so already

    $ go mod init module-name
  2. Add goverter as dependency to your project

    $ go get github.com/jmattheis/goverter
  3. Create your converter interface and mark it with a comment containing goverter:converter

    input.go

    package example
    
    // goverter:converter
    type Converter interface {
      Convert(source []Input) []Output
    }
    
    type Input struct {
      Name string
      Age int
    }
    type Output struct {
      Name string
      Age int
    }
  4. Run goverter:

    $ go run github.com/jmattheis/goverter/cmd/goverter module-name-in-full
    # example
    $ go run github.com/jmattheis/goverter/cmd/goverter github.com/jmattheis/goverter/example/simple
    
  5. goverter created a file at ./generated/generated.go, it may look like this:

    package generated
    
    import simple "github.com/jmattheis/goverter/example/simple"
    
    type ConverterImpl struct{}
    
    func (c *ConverterImpl) Convert(source []simple.Input) []simple.Output {
      simpleOutputList := make([]simple.Output, len(source))
      for i := 0; i < len(source); i++ {
        simpleOutputList[i] = c.simpleInputToSimpleOutput(source[i])
      }
      return simpleOutputList
    }
    func (c *ConverterImpl) simpleInputToSimpleOutput(source simple.Input) simple.Output {
      var simpleOutput simple.Output
      simpleOutput.Name = source.Name
      simpleOutput.Age = source.Age
      return simpleOutput
    }

Docs

Rename converter

With goverter:name you can set the name of the generated converter struct.

input.go

// goverter:converter
// goverter:name RenamedConverter
type BadlyNamed interface {
    // .. methods
}

output.go

type RenamedConverter struct {}

func (c *RenamedConverter) ...

Extend with custom implementation

With goverter:extend you can instruct goverter to use an implementation of your own. You can pass multiple function names to goverter:extend, or define the tag multiple times.

See house example sql.NullString

input.go

// goverter:converter
// goverter:extend IntToString
type Converter interface {
    Convert(Input) Output
}
type Input struct {Value int}
type Output struct {Value string}

// You must atleast define a source and target type. Meaning one parameter and one return.
// You can use any type you want, like struct, maps and so on.
func IntToString(i int) string {
    return fmt.Sprint(i)
}

Reuse generated converter

If you need access to the generated converter, you can define it as first parameter.

func IntToString(c Converter, i int) string {
    // c.DoSomething()..
    return fmt.Sprint(i)
}

Errors

Sometimes, custom conversion may fail, in this case goverter allows you to define a second return parameter which must be type error.

// goverter:converter
// goverter:extend IntToString
type Converter interface {
    Convert(Input) (Output, error)
}

type Input struct {Value int}
type Output struct {Value string}

func IntToString(i int) (string, error) {
    if i == 0 {
        return "", errors.New("zero is not allowed")
    }
    return fmt.Sprint(i)
}

Note: If you do this, methods on the interface that'll use this custom implementation, must also return error as second return.

Struct field mapping

With goverter:map you can map fields on structs that have the same type.

goverter:map takes 2 parameters.

  1. source field path (fields are separated by .)
  2. target field name
// goverter:converter
type Converter interface {
    // goverter:map Name FullName
    // goverter:map Nested.Age Age
    Convert(source Input) Output
}

type Input struct {
    Name string
    Nested NestedInput
}
type NestedInput struct {
    Age int
}
type Output struct {
    FullName string
    Age int
}

Struct identity mapping

With goverter:mapIdentity you can instruct goverter to use the source struct as source for the conversion to the target property.

goverter:mapIdentity takes multiple field names separated by space .

// goverter:converter
type Converter interface {
    // goverter:mapIdentity Address
    ConvertPerson(source Person) APIPerson
}

type Person struct {
    Name   string
    Street string
    City   string
}

type APIPerson struct {
    Name    string
    Address APIAddress
}

type APIAddress struct {
    Street string
    City   string
}

In the example goverter will fill Address by creating a converter from Person to APIAddress. Example generated code:

func (c *ConverterImpl) ConvertPerson(source execution.Person) execution.APIPerson {
    var structsAPIPerson execution.APIPerson
    structsAPIPerson.Name = source.Name
    structsAPIPerson.Address = c.structsPersonToStructsAPIAddress(source)
    return structsAPIPerson
}
func (c *ConverterImpl) structsPersonToStructsAPIAddress(source execution.Person) execution.APIAddress {
    var structsAPIAddress execution.APIAddress
    structsAPIAddress.Street = source.Street
    structsAPIAddress.City = source.City
    return structsAPIAddress
}

Struct ignore field

With goverter:ignore you can ignore fields on the target struct

goverter:ignore takes multiple field names separated by space .

// goverter:converter
type Converter interface {
    // goverter:ignore Age
    Convert(source Input) Output
}

type Input struct {
    Name string
}
type Output struct {
    Name string
    Age int
}

Versioning

goverter use SemVer for versioning the cli.

License

This project is licensed under the MIT License - see the LICENSE file for details

Logo by MariaLetta

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].