### Install Goverter Binary Source: https://context7.com/jmattheis/goverter/llms.txt Install the goverter binary using `go install`. This is the recommended method for one-time installation. ```bash # Install binary (once) go install github.com/jmattheis/goverter/cmd/goverter@v1.9.4 ``` -------------------------------- ### Install Goverter Binary Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/install.md Use 'go install' to install the Goverter binary. Ensure your $GOPATH/bin is on your system's PATH. ```bash-vue $ go install github.com/jmattheis/goverter/cmd/goverter@{{ libVersion }} ``` -------------------------------- ### Database Context Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/context.md Demonstrates using context arguments for database-related operations. This example shows the input Go code and its generated output. ```go package database //go:generate goverter -type=Converter -output=generated/generated.go . type Converter interface { //go:context database.Connection ToDTO(source User) (UserDTO, error) } ``` ```go package database import ( "database/sql" "fmt" ) type Connection struct { DB *sql.DB } type User struct { Name string Age int } type UserDTO struct { FullName string YearsOld int } type ConverterImpl struct { connection Connection } func (s *ConverterImpl) ToDTO(source User) (UserDTO, error) { return UserDTO{ FullName: fmt.Sprintf("%s (%d)", source.Name, source.Age), YearsOld: source.Age, }, nil } ``` -------------------------------- ### Multiple Output Files Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/output.md Demonstrates how different converters can share the same output file if their output package is identical. This example shows multiple output files being generated. ```go package main // goverter:converter // goverter:output:file ../generated/generated.go // goverter:output:package generated type Root interface { Convert(ctx context.Context, source []string) ([]string, error) } ``` ```go package c // goverter:converter // goverter:output:file ../generated/generated.go // goverter:output:package generated type Input interface { Convert(ctx context.Context, source []string) ([]string, error) } ``` ```go package generated // Code generated by goverter // DO NOT EDIT import "context" type Root struct{ ctx context.Context } func NewRoot(ctx context.Context) *Root { return &Root{ctx: ctx} } func (s *Root) Convert(ctx context.Context, source []string) ([]string, error) { var destination = make([]string, len(source)) for i, v := range source { destination[i] = v + "c" } return destination, nil } ``` ```go package generated // Code generated by goverter // DO NOT EDIT import "context" type Input struct{ ctx context.Context } func NewInput(ctx context.Context) *Input { return &Input{ctx: ctx} } func (s *Input) Convert(ctx context.Context, source []string) ([]string, error) { var destination = make([]string, len(source)) for i, v := range source { destination[i] = v + "c" } return destination, nil } ``` -------------------------------- ### Example: Output Raw Code Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/output.md Demonstrates the use of raw output code in Goverter. This example includes both the input Go file and the generated Go file. ```go package main // Input struct type Input struct { Name string } // Output struct type Output struct { Name string } //go:generate goverter -type Output -output generated/generated.go func Convert(input Input) Output ``` ```go // Code generated by goverter // DO NOT EDIT package generated // Input struct type Input struct { Name string } // Output struct type Output struct { Name string } // Convert implements goverter.Converter func Convert(input Input) Output { return Output{ Name: input.Name, } } ``` -------------------------------- ### Date Formatting Example Input Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/signature.md This is the input Go code for a date formatting example, demonstrating how context parameters can be used. ```go package main import ( "time" ) //go:generate goverter ./... type DateFormat struct { Time time.Time } type DateFormatDTO struct { Time string } func NewDateFormatDTO(time time.Time) DateFormatDTO { return DateFormatDTO{ Time: time.Format(time.RFC3339), } } ``` -------------------------------- ### Example Usage with github.com/goverter/patherr Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/wrapErrorsUsing.md Provides an example of using the github.com/goverter/patherr package to satisfy the requirements for wrapping errors and generating path elements. ```go package main import ( "fmt" "github.com/goverter/goverter" "github.com/goverter/goverter/patherr" "github.com/goverter/goverter/test/model" ) //go:generate goverter .. //go:generate goverter .. --wrap-errors-using github.com/goverter/goverter/patherr func main() { var source *model.Source var target *model.Target converter := NewConverter(patherr.NewConverter()) converter.Convert(source, &target) fmt.Println(target) } ``` ```go package main import ( "fmt" "github.com/goverter/goverter" "github.com/goverter/goverter/patherr" "github.com/goverter/goverter/test/model" ) //go:generate goverter .. //go:generate goverter .. --wrap-errors-using github.com/goverter/goverter/patherr func main() { var source *model.Source var target *model.Target converter := NewConverter(patherr.NewConverter()) converter.Convert(source, &target) fmt.Println(target) } ``` ```go module github.com/goverter/goverter go 1.16 require ( github.com/goverter/goverter v0.0.0 github.com/goverter/goverter/patherr v0.0.0 github.com/goverter/goverter/test v0.0.0 ) ``` -------------------------------- ### Verify Goverter Installation Source: https://context7.com/jmattheis/goverter/llms.txt Check if the goverter binary is installed correctly by running the `goverter version` command. ```bash # Verify installation goverter version ``` -------------------------------- ### Enable matchIgnoreCase Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/matchIgnoreCase.md Example demonstrating how to enable the matchIgnoreCase setting. This instructs Goverter to match fields ignoring differences in capitalization. ```go package main // goverter: converters // goverter: matchIgnoreCase type SimpleConverter interface { InputToOutput(input *Input) Output } type Input struct { FirstName string LastName string } type Output struct { FirstName string LastName string } ``` ```go // Code generated by goverter type SimpleConverterImpl struct { } func (s *SimpleConverterImpl) InputToOutput(input *Input) Output { var output Output output.FirstName = input.FirstName output.LastName = input.LastName return output } ``` -------------------------------- ### Example: Convert to Protobuf Generated Structs Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/struct.md Demonstrates converting Go structs to protobuf generated structs. This example includes Go input, a proto definition, compiled protobuf Go code, and generated Go code. ```go package main import ( "fmt" "github.com/jmattheis/goverter/example/protobuf/pb" ) //go:generate goverter -type MyConverter -output ./generated/generated.go . type MyConverter struct{} func (s MyConverter) convertEvent(input *pb.Event) *Event { return &Event{ Name: input.GetName(), Value: input.GetValue(), } } func main() { converter := MyConverter{} ``` ```protobuf syntax = "proto3"; package pb; option go_package = "./pb"; message Event { string name = 1; int64 value = 2; } ``` ```go package pb // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.1 // protoc v3.21.7 import ( fmt "fmt" "strconv" ) // String is not generated here, but is needed for the example func (x *Event) String() string { return "Event(name:" + x.Name + ", value:" + strconv.FormatInt(x.Value, 10) + ")" } // Event represents an event. type Event struct { Name string Value int64 } // GetName returns the name of the event. func (x *Event) GetName() string { if x != nil { return x.Name } return "" } // GetValue returns the value of the event. func (x *Event) GetValue() int64 { if x != nil { return x.Value } return 0 } ``` ```go package generated import ( "github.com/jmattheis/goverter/example/protobuf/pb" ) type Event struct { Name string Value int64 } type MyConverterImpl struct { } func (s MyConverterImpl) convertEvent(input *pb.Event) *Event { return &Event{ Name: input.GetName(), Value: input.GetValue(), } } ``` -------------------------------- ### Run Goverter Binary Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/install.md Execute the installed Goverter binary to view its help message. ```bash $ goverter --help ``` -------------------------------- ### Date Format Context Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/context.md Illustrates using context arguments for date formatting. This example includes the input Go code and the generated Go code. ```go package dateformat //go:generate goverter -type=Converter -output=generated/generated.go . type Converter interface { //go:context time.Time ToDTO(source Birthday) (BirthdayDTO, error) } ``` ```go package dateformat import ( "fmt" "time" ) type Birthday struct { Name string Date time.Time } type BirthdayDTO struct { Name string DateOfBirth string } type ConverterImpl struct { tTime time.Time } func (s *ConverterImpl) ToDTO(source Birthday) (BirthdayDTO, error) { return BirthdayDTO{ Name: source.Name, DateOfBirth: fmt.Sprintf("%s", source.Date.Format("2006-01-02")) }, nil } ``` -------------------------------- ### Goverter Variables Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/variables.md Demonstrates the use of the `variables` setting in Goverter for generating variable implementations. This example includes input, common, and generated Go code. ```go package assignvariables type Source struct { Name string Age int } type Target struct { Name string Age int } // goverter:variables // goverter:assign func Convert(s Source) Target { return Target{} } ``` ```go package common type AnotherSource struct { Value string } type AnotherTarget struct { Value string } // goverter:assign func Convert(s AnotherSource) AnotherTarget { return AnotherTarget{} } ``` ```go // Code generated by goverter --- DO NOT EDIT. package assignvariables // AssignVariables assigns variables from a Source to a Target. func (s *Source) AssignVariables(t *Target) { t.Name = s.Name t.Age = s.Age } ``` -------------------------------- ### Simple Converter Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/converter.md This snippet shows a basic example of input and generated Go code for a converter. The input.go file defines the interface to be converted, and generated.go shows the implementation generated by Goverter. ```go package simple type Simple struct { Val string } type SimpleConverter interface { Convert(s Simple) string } ``` ```go package simple // generated by github.com/jmattheis/goverter // unless otherwise marked type SimpleConverterImpl struct { } func (s *SimpleConverterImpl) Convert(simple Simple) string { return simple.Val } ``` -------------------------------- ### Goverter Generate Command Examples Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/cli.md Examples of how to use the `goverter gen` command to generate converters. These demonstrate specifying single packages, multiple packages using the '...' pattern, and packages from a remote repository. ```bash goverter gen ./example/simple ./example/complex ``` ```bash goverter gen ./example/... ``` ```bash goverter gen github.com/jmattheis/goverter/example/simple ``` -------------------------------- ### Custom Enum Transformer Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/enum.md This example demonstrates how to set up a custom enum transformer with a trim-prefix functionality. It includes the Goverter runner, the input struct, and the generated output. ```go package main import ( "fmt" "strings" "github.com/jmattheis/goverter/v2" ) //go:generate goverter .. //go:generate goverter .. --exclude-generate-from type InputEnum int const ( InputEnumA InputEnum = iota InputEnumB ) func (e InputEnum) String() string { switch e { case InputEnumA: return "InputEnumA" case InputEnumB: return "InputEnumB" default: return "" } } type OutputEnum int const ( OutputEnumA OutputEnum = iota OutputEnumB ) func (e OutputEnum) String() string { switch e { case OutputEnumA: return "OutputEnumA" case OutputEnumB: return "OutputEnumB" default: return "" } } type InputStruct struct { Value InputEnum } type OutputStruct struct { Value OutputEnum } func NewConverter() *Converter { return &Converter{} } type Converter struct { TrimPrefix string } func (c *Converter) InputStructToOutputStruct(input InputStruct) OutputStruct { return OutputStruct{ Value: c.inputEnumToOutputEnum(input.Value), } } func (c *Converter) inputEnumToOutputEnum(input InputEnum) OutputEnum { var output OutputEnum inputStr := input.String() outputStr := strings.TrimPrefix(inputStr, c.TrimPrefix) sswitch outputStr { case "A": output = OutputEnumA case "B": output = OutputEnumB default: panic("invalid enum value") } return output } ``` ```go package main type InputEnum int const ( InputEnumA InputEnum = iota InputEnumB ) func (e InputEnum) String() string { switch e { case InputEnumA: return "InputEnumA" case InputEnumB: return "InputEnumB" default: return "" } } type OutputEnum int const ( OutputEnumA OutputEnum = iota OutputEnumB ) func (e OutputEnum) String() string { switch e { case OutputEnumA: return "OutputEnumA" case OutputEnumB: return "OutputEnumB" default: return "" } } type InputStruct struct { Value InputEnum } type OutputStruct struct { Value OutputEnum } ``` ```go // Code generated by goverter --- DO NOT EDIT. package generated // Converter.InputStructToOutputStruct func (_a *Converter) InputStructToOutputStruct(_a0 main.InputStruct) main.OutputStruct { var _a1 main.OutputEnum _a2 := _a0.Value.String() _a3 := strings.TrimPrefix(_a2, _a.TrimPrefix) sswitch _a3 { case "A": _a1 = main.OutputEnumA case "B": _a1 = main.OutputEnumB default: panic("invalid enum value") } return main.OutputStruct{ Value: _a1, } } ``` -------------------------------- ### Goverter Example: useUnderlyingTypeMethods Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/useUnderlyingTypeMethods.md This example demonstrates the use of the useUnderlyingTypeMethods setting in Goverter. It shows how Goverter can utilize existing methods that operate on underlying types for conversions, in addition to methods directly matching the named types. ```go package main type InputID int type OutputID int func (i InputID) ToOutputID() OutputID { return OutputID(i + 1) } //go:generate goverter ./... //goverter:useUnderlyingTypeMethods func Convert(input InputID) OutputID { return OutputID(input) } ``` ```go // Code generated by goverter // InputIDToOutputID is an autogenerated method returning OutputID from InputID. func InputIDToOutputID(input InputID) OutputID { return input.ToOutputID() } ``` -------------------------------- ### Date Formatting Example Generated Code Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/signature.md This is the generated Go code for the date formatting example, showing the implementation of the conversion function. ```go // Code generated by goverteršč. DO NOT EDIT. package main import ( "time" ) // DateFormatDTOFromDateFormat is an autogenerated method. // It converts DateFormat to DateFormatDTO. func DateFormatDTOFromDateFormat(input DateFormat) DateFormatDTO { return DateFormatDTO{ Time: input.Time.Format(time.RFC3339), } } ``` -------------------------------- ### Output Format: Struct Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/output.md Generates an implementation of the conversion interface by creating a struct with methods. This is the default output format. ```go package main // goverter:converter // goverter:output:file generated/generated.go type Converter interface { Convert(string) string } ``` ```go package main // goverter:ignore func (s *Simple) Convert(input string) string { return input + "c" } ``` ```go package generated // Code generated by goverter // DO NOT EDIT type Converter struct{ } func NewConverter() Converter { return Converter{} } func (s Converter) Convert(input string) string { var destination string destination = input + "c" return destination } ``` -------------------------------- ### Output Format: Function Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/output.md Generates a separate function for each method in the conversion interface. This can be useful for simpler conversion needs. ```go package main // goverter:converter // goverter:output:file generated/generated.go // goverter:output:format function type Converter interface { Convert(string) string } ``` ```go package main // goverter:ignore func (s *Simple) Convert(input string) string { return input + "c" } ``` ```go package generated // Code generated by goverter // DO NOT EDIT func Convert(input string) string { var destination string destination = input + "c" return destination } ``` -------------------------------- ### Interface to Struct Conversion Example Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/format.md Demonstrates the default interface to struct conversion. Requires initialization of the implementation struct and calling methods on it to execute conversions. ```go package input type Source struct { Value string } type Target struct { Value string } ``` ```go package common type Common struct { Value string } ``` ```go package generated import ( input "github.com/jmattheis/goverter/example/format/interfacetostruct" common "github.com/jmattheis/goverter/example/format/common" ) type ConverterImpl struct { } func (s *ConverterImpl) InputToTarget(input input.Source) input.Target { return input.Target{Value: input.Value} } func (s *ConverterImpl) InputToCommon(input input.Source) common.Common { return common.Common{Value: input.Value} } ``` -------------------------------- ### Output Format: Assign Variable Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/output.md Generates an init function that assigns an implementation for all function variables. This format is useful for initializing converters. ```go package main // goverter:converter // goverter:output:file input.gen.go // goverter:output:format assign-variable type Converter interface { Convert(string) string } ``` ```go package main // goverter:ignore func (s *Simple) Convert(input string) string { return input + "c" } ``` ```go package main // Code generated by goverter // DO NOT EDIT var ConverterImpl Converter func init() { ConverterImpl = NewConverter() } ``` -------------------------------- ### Run Goverter with Go Run Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/install.md Execute Goverter directly using 'go run' without installing a binary. This method may take longer on the first run as Go compiles the tool. ```bash-vue $ go run github.com/jmattheis/goverter/cmd/goverter@{{ libVersion }} --help ``` -------------------------------- ### Enum Key Mapping Example Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/enum.md Demonstrates mapping differently named keys between source and target enums using the `enum:map` directive. ```go package map //go:generate goverter ./... //goverter:enum:map ``` ```go package input type IotaEnum int const ( First IotaEnum = iota Second Third ) ``` ```go package output type StringEnum string const ( Alpha StringEnum = "alpha" Beta StringEnum = "beta" Gamma StringEnum = "gamma" ) ``` ```go package map import ( "input" "output" ) //go:generate goverter ./... //goverter:enum:map func ConvertIotaEnumToStringEnum(input input.IotaEnum) output.StringEnum { panic("goverter: please implement ConvertIotaEnumToStringEnum") } ``` -------------------------------- ### Wrap Errors Example in Go Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/wrapErrors.md Demonstrates the usage of the wrapErrors setting. Enable this setting to include troubleshooting information in errors returned by extend methods. ```go package main // @TypeConverter.WrapErrors // // @TypeConverter // Target: main.Target // Source: main.Source func Convert(source Source) Target { panic("implement me") } type Source struct { Value string } type Target struct { Value string } ``` ```go // Code generated by github.com/jmattheis/goverter // DO NOT EDIT package main type Target struct { Value string } type Source struct { Value string } func Convert(source Source) Target { var target Target // Possible error during conversion of field Value // Field: Target.Value // Source Field: Source.Value // Error: target.Value = source.Value return target } ``` -------------------------------- ### Generated Converter Implementation Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/getting-started.md This is an example of the Go code Goverter generates for your converter interface. It includes implementations for `Convert` and `ConvertItems`. ```go package generated import example "goverter/example" type ConverterImpl struct{} func (c *ConverterImpl) Convert(source example.Input) example.Output { var exampleOutput example.Output exampleOutput.Name = source.Name exampleOutput.Age = source.Nested.AgeInYears return exampleOutput } func (c *ConverterImpl) ConvertItems(source []example.Input) []example.Output { var exampleOutputList []example.Output if source != nil { exampleOutputList = make([]example.Output, len(source)) for i := 0; i < len(source); i++ { exampleOutputList[i] = c.Convert(source[i]) } } return exampleOutputList } ``` -------------------------------- ### Interface to Functions Conversion Example Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/format.md Shows the interface to functions conversion. Conversions are executed directly, but the interface is only for defining conversions and not otherwise usable. The `map` method with converter use-case is unsupported. ```go package interfacefunction type Source struct { Value string } type Target struct { Value string } ``` ```go package common type Common struct { Value string } ``` ```go package generated import ( input "github.com/jmattheis/goverter/example/format/interfacefunction" common "github.com/jmattheis/goverter/example/format/common" ) func InputToTarget(input input.Source) input.Target { return input.Target{Value: input.Value} } func InputToCommon(input input.Source) common.Common { return common.Common{Value: input.Value} } ``` -------------------------------- ### Add Goverter as Dependency Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/install.md Add Goverter to your project's go.mod file using 'go get'. This ensures all developers use the same Goverter version. ```bash-vue $ go get github.com/jmattheis/goverter@{{ libVersion }} ``` -------------------------------- ### Output Package: Normalizing Reserved Characters Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/output.md Demonstrates how Goverter normalizes reserved characters in the package name. For example, hyphens and underscores are removed. ```go // goverter:converter // goverter:output:package example.org/simple/my-cool_package type Converter interface { Convert([]string) []string } ``` -------------------------------- ### Use Generated Implementation in the Same Package Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/output-same-package.md This example shows how to use the generated converter implementation within the same package. Ensure the generated file includes the necessary build constraint to avoid compilation errors. ```go package samepackage import "errors" func ValidateAndConvert(source *Input) (*Output, error) { if source.Name == "" { return nil, errors.New("Name may not be nil") } c := &ConverterImpl{} return c.Convert(source) } ``` ```go package samepackage // Input is a sample input struct type Input struct { Name string } // Output is a sample output struct type Output struct { Value int } //go:generate goverter .. --output generated.go ``` ```go package samepackage // Input is a sample input struct type Input struct { Name string } // Output is a sample output struct type Output struct { Value int } //go:generate goverter .. --output generated.go ``` -------------------------------- ### Enum Definition Example Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/enum.md Illustrates Go types that qualify as enums for Goverter, featuring an iota-based enum and its string representation. ```go package unknown type IotaEnum int const ( First IotaEnum = iota Second Third ) ``` ```go package unknown type StringEnum string const ( FirstString StringEnum = "first" SecondString StringEnum = "second" ThirdString StringEnum = "third" ) ``` -------------------------------- ### Input Go Code for skipCopySameType Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/skipCopySameType.md This Go code demonstrates the input structure for testing the skipCopySameType setting. Ensure this code is present in your project to observe the setting's behavior. ```go package main type Source struct { Value string } type Target struct { Value string } // goverter:skipCopySameType // goverter:converter type SourceToTargetConverter interface { Convert(source Source) Target } ``` -------------------------------- ### Variables to Assign-Variable Conversion Example Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/format.md Illustrates the default variables to assign-variable conversion. Conversions can be executed directly without initializing a struct, but may have runtime overhead. ```go package assignvariables type Source struct { Value string } type Target struct { Value string } ``` ```go package common type Common struct { Value string } ``` ```go package assignvariables import ( common "github.com/jmattheis/goverter/example/format/common" ) func InputToTarget(input Source) Target { return Target{Value: input.Value} } func InputToCommon(input Source) common.Common { return common.Common{Value: input.Value} } ``` -------------------------------- ### Struct Comment Example in Go Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/struct.md Demonstrates how to use `struct:comment` to add comments to generated Go structs. Configure this setting via CLI or conversion comments. ```go package main type Source struct { Name string } type Target struct { Name string } ``` ```go // Code generated by goverter package target type Target struct { // Name is a comment Name string } ``` -------------------------------- ### Goverter Generate with Global Settings Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/cli.md Example of using the `goverter gen` command with global settings applied. The `-g` flag allows specifying options like 'ignoreMissing' and 'skipCopySameType' for all converters. ```bash goverter gen -g 'ignoreMissing no' -g 'skipCopySameType' ./simple ``` -------------------------------- ### Input Go Struct for ignoreMissing Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/ignoreMissing.md This Go struct demonstrates the input structure for the ignoreMissing setting. It contains fields that might be missing in the target struct. ```go package ignoremissing type Source struct { Value1 string Value2 string Value3 string } type Target struct { Value1 string Value3 string } ``` -------------------------------- ### Apply Global Settings to Converters Source: https://context7.com/jmattheis/goverter/llms.txt Apply global settings to all converters during generation using the `-g` or `-global` flags. This example enables error wrapping and ignores missing fields. ```bash # Apply global settings to all converters (e.g., enable error wrapping everywhere) goverter gen -g 'wrapErrors yes' -g 'ignoreMissing no' ./... ``` -------------------------------- ### Output Package: Inferring Package Path Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/output.md Goverter infers the package path from `output:file` if it's within the same Go module. This example shows how to explicitly set the package path. ```go // goverter:converter // goverter:output:package example.org/simple/mypackage type Converter interface { Convert([]string) []string } ``` -------------------------------- ### Output Package: Overwriting Inferred Package Name Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/output.md Allows overwriting the inferred package name using `output:package PACKAGE:NAME`. This example sets a specific package name. ```go // goverter:converter // goverter:output:package example.org/simple/my-cool_package:overriddenname type Converter interface { Convert([]string) []string } ``` -------------------------------- ### Generated Go Code for skipCopySameType Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/skipCopySameType.md This is the generated Go code produced by Goverter when the skipCopySameType setting is applied. It shows how Goverter optimizes copying when source and target types are the same. ```go package main // generated by github.com/jmattheis/goverter // unless explicitly marked type SourceToTargetConverterImpl struct { } func (s *SourceToTargetConverterImpl) Convert(source Source) Target { return Target{ Value: source.Value, } } ``` -------------------------------- ### Define Struct Name with `name` Setting Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/name.md This example demonstrates how to use the `name` setting to define a custom name for the generated struct. The input Go file defines an interface, and the generated file shows the struct with the specified name. ```go package main //go:generate goverter . -type=Greeter -output=generated/generated.go -name=CustomGreeter type Greeter interface { Greet(name string) string } ``` ```go package main // Code generated by goverter // DO NOT EDIT type CustomGreeter struct { } func (s CustomGreeter) Greet(name string) string { panic("implement me") } ``` -------------------------------- ### Initialize Go Modules Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/install.md If you don't have a Go modules project, initialize one using 'go mod init'. ```bash $ go mod init module-name ``` -------------------------------- ### Goverter CLI Help Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/cli.md Displays the usage instructions and available options for the Goverter CLI. Use this to understand command structure and parameters. ```bash goverter help ``` -------------------------------- ### Initialize Go Module Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/getting-started.md Use this command to initialize a new Go modules project if you haven't already. ```bash go mod init module-name ``` -------------------------------- ### Ignore Unexported Fields Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/ignoreUnexported.md Demonstrates the use of the ignoreUnexported setting to handle unexported fields in struct conversions. This example shows the input Go code and the generated output. ```go package main import "fmt" type Source struct { Value int unexportedValue int } type Target struct { Value int unexportedValue int } //goverter:ignoreUnexported func main() { var source Source source.Value = 1 source.unexportedValue = 2 ttarget := Target{Value: 1, unexportedValue: 2} converted := Convert(source) if converted.Value != ttarget.Value || converted.unexportedValue != ttarget.unexportedValue { panic("conversion failed") } fmt.Println("conversion successful") } ``` ```go // Code generated by goverter --- DO NOT EDIT. package main // Convert implements main.Converter.Convert. func Convert(s Source) Target { var t Target t.Value = s.Value t.unexportedValue = s.unexportedValue return t } ``` -------------------------------- ### Inheritance and Precedence of Settings Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/define-settings.md Demonstrates how settings are inherited from CLI or converter interfaces to methods, with method-specific settings taking precedence. This allows for global defaults with specific overrides. ```go // goverter:converter // goverter:feature1 yes type Converter interface { Convert1(source Input1) Output1 Convert2(source Input2) Output2 // goverter:feature1 no Convert3(source Input3) Output3 } ``` -------------------------------- ### Input Struct for autoMap Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/autoMap.md This Go code defines the input structure used in the `autoMap` example. It includes nested structs that will be mapped. ```go package main type SubStruct struct { Value string } type Nested struct { Sub SubStruct } type Input struct { Nested Nested Other string } ``` -------------------------------- ### Extend with Context Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/extend.md Demonstrates extending conversion logic with context awareness, such as date formatting. ```go package main import "time" type Source struct { Date time.Time } type Target struct { Date string } // Goverter: extend func extend(ctx context.Context, s Source) Target { return Target{Date: s.Date.Format("2006-01-02")} } //go:generate goverter . type Converter interface { Convert(context.Context, Source) Target } ``` ```go package main import "time" // Converter is an interface generated by Goverter. // It converts Source to Target with context. type ConverterImpl struct{} func (s *ConverterImpl) Convert(ctx context.Context, source Source) Target { return Target{Date: source.Date.Format("2006-01-02")} } ``` -------------------------------- ### Configure Goverter for Same-Package Output Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/output-same-package.md Configure the 'output' setting to place the generated file in the same directory. This is a prerequisite for using the implementation within the same package. ```go package samepackage //go:generate goverter .. --output samepackage/generated.go ``` ```go package samepackage // Input is a sample input struct type Input struct { Name string } // Output is a sample output struct type Output struct { Value int } //go:generate goverter .. --output generated.go ``` ```go package samepackage // Input is a sample input struct type Input struct { Name string } // Output is a sample output struct type Output struct { Value int } //go:generate goverter .. --output generated.go ``` -------------------------------- ### Run Goverter from Dependencies Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/install.md Execute Goverter after adding it as a dependency, ensuring consistent version usage across the development team. ```bash $ go run github.com/jmattheis/goverter/cmd/goverter --help ``` -------------------------------- ### Goverter Optional Source Signatures Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/signature.md Demonstrates function signatures that support optional source parameters, including context parameters. ```go func ConvertOne() A { /***/ } // A=target func ConvertTwo() (B, error) { /***/ } // A=target; error=target_error func ConvertThree(input A) B { /***/ } // A=source; B=target func ConvertFour(input A) (B, error) { /***/ } // A=source; B=target; error=target_error // goverter:context one // goverter:context two func ConvertFour(one A, two B) C { /***/ } // A=context; B=context; C=target // goverter:context one // goverter:context two func ConvertFive(input A, one B, two C) D { /***/ } // A=source; B=context; C=context; D=target ``` -------------------------------- ### Control Output File and Package with `output:file` and `output:package` Source: https://context7.com/jmattheis/goverter/llms.txt Configure the output file path and package for generated code using `output:file` and `output:package`. The `output:format` setting determines whether to generate a struct, standalone functions, or an init function for variable assignment. ```go // goverter:converter // goverter:output:file ../api/generated.go // goverter:output:package github.com/myorg/myapp/api:apiconverter // goverter:output:format function type Converter interface { Convert(Input) Output } // output:format options: // struct (default) — generates a struct with methods // function — generates standalone functions // assign-variable — generates an init() that assigns function variables ``` ```go // assign-variable example input // goverter:variables // goverter:output:format assign-variable var ( Convert func(Input) Output ) // Generated init(): // func init() { // Convert = converterImplConvert // } ``` -------------------------------- ### Ignore Fields in Goverter Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/ignore.md Use the 'ignore' setting within a method comment to prevent specific fields from being converted. This example shows ignoring the 'Name' field. ```go package main //goverter type Converter interface { // ignore Name ToSomething(from Input) Something } type Input struct { Name string Age int } type Something struct { Name string Age int } ``` ```go package main // Code generated by github.com/jmattheis/goverter, DO NOT EDIT. import structpb "google.golang.org/protobuf/types/known/structpb" // ToSomethingImpl implements the Converter interface. func ToSomethingImpl(from Input) Something { var to Something // Name is ignored to.Age = from.Age return to } ``` -------------------------------- ### Ignore Unexported Fields with Protobuf Example Source: https://github.com/jmattheis/goverter/blob/main/docs/guide/unexported-field.md Use the 'ignore' directive to skip unexported fields, such as those generated by protobuf. This is useful when these fields are internal and not meant to be set manually. ```go package protobuf //go:generate go run github.com/jmattheis/goverter/cmd/goverter ./generated //go:generate protoc --go_out=. --go_opt=paths=source_relative event.proto // @goverter: ignore //go:generate go run github.com/jmattheis/goverter/cmd/goverter ./generated type ProtobufConverter interface { // ignore all unexported fields Convert(source *Event) (*Event, error) } ``` ```proto syntax = "proto3"; package protobuf; option go_package = ".;pb"; message Event { string name = 1; int32 value = 2; } ``` ```go package protobuf // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.1 // protoc v3.17.3 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ protoreflect.Version = protoreflect.MaxVersion // Are there too many rev dependencies? _ syncdependency.MaxVersion = syncdependency.MaxVersion ) var File_event_proto protoreflect.FileDescriptor type Event struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Name string `protobuf:"bytes,1,opt,name=name,proto3" Value int32 `protobuf:"varint,2,opt,name=value,proto3" } func (x *Event) Reset() { *x = Event{} protoimpl.Reset(x.state) } func (x *Event) String() string { return protoimpl.X.MessageStringOf(x) } func (*Event) ProtoMessage() {} func (x *Event) ProtoReflect() protoreflect.Message { return protoreflect.MessageOf(x.state.Bytes()) } // Deprecated: Use Event.ProtoReflect.Descriptor instead. func GetMessageDescriptor() protoreflect.Descriptor { return file_event_proto.MessageOf(0) } func (x *Event) ProtoReflect().Descriptor() protoreflect.Descriptor { return file_event_proto.MessageOf(0) } // Used by the proto package; DO NOT EDIT. var _ proto.Message const { // Name FIELDNUMBER_NAME = 1, // Value FIELDNUMBER_VALUE = 2, } func (x *Event) GetName() string { if x != nil { return x.Name } return "" } func (x *Event) GetValue() int32 { if x != nil { return x.Value } return 0 } func (x *Event) Size() int { return protoimpl.X.Size(x) } func (x *Event) MarshalToSizedBuffer(dAtA []byte) (int, error) { return protoimpl.X.MarshalToSizedBuffer(dAtA, x) } func (x *Event) Marshal() (dAtA []byte, err error) { return protoimpl.X.Marshal(x) } func (x *Event) Unmarshal(dAtA []byte) error { return protoimpl.X.Unmarshal(dAtA, x) } func (x *Event) XXX_Unmarshal(b []byte) error { return protoimpl.X.Unmarshal(b, x) } func (x *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return protoimpl.X.Marshal(b, deterministic, x) } func (x *Event) XXX_Merge(src proto.Message) { protoimpl.X.Merge(x, src) } func (x *Event) XXX_Size() int { return protoimpl.X.Size(x) } func (x *Event) XXX_DiscardUnknown() { protoimpl.X.DiscardUnknown(x) } var xxx_messageInfo_Event protoimpl.MessageInfo func (x *Event) Reset() { *x = Event{} protoimpl.Reset(x.state) } func (x *Event) String() string { return protoimpl.X.MessageStringOf(x) } func (*Event) ProtoMessage() {} func (x *Event) ProtoReflect() protoreflect.Message { return protoreflect.MessageOf(x.state.Bytes()) } // Deprecated: Use Event.ProtoReflect.Descriptor instead. func GetMessageDescriptor() protoreflect.Descriptor { return file_event_proto.MessageOf(0) } func (x *Event) ProtoReflect().Descriptor() protoreflect.Descriptor { return file_event_proto.MessageOf(0) } // Used by the proto package; DO NOT EDIT. var _ proto.Message const { // Name FIELDNUMBER_NAME = 1, // Value FIELDNUMBER_VALUE = 2, } func (x *Event) GetName() string { if x != nil { return x.Name } return "" } func (x *Event) GetValue() int32 { if x != nil { return x.Value } return 0 } func (x *Event) Size() int { return protoimpl.X.Size(x) } func (x *Event) MarshalToSizedBuffer(dAtA []byte) (int, error) { return protoimpl.X.MarshalToSizedBuffer(dAtA, x) } func (x *Event) Marshal() (dAtA []byte, err error) { return protoimpl.X.Marshal(x) } func (x *Event) Unmarshal(dAtA []byte) error { return protoimpl.X.Unmarshal(dAtA, x) } func (x *Event) XXX_Unmarshal(b []byte) error { return protoimpl.X.Unmarshal(b, x) } func (x *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return protoimpl.X.Marshal(b, deterministic, x) } func (x *Event) XXX_Merge(src proto.Message) { protoimpl.X.Merge(x, src) } func (x *Event) XXX_Size() int { return protoimpl.X.Size(x) } func (x *Event) XXX_DiscardUnknown() { protoimpl.X.DiscardUnknown(x) } var xxx_messageInfo_Event protoimpl.MessageInfo func init() { file_event_proto_init() } func file_event_proto_init() { panic(fmt.x.String("not implemented")) } ``` ```go package protobuf //go:generate go run github.com/jmattheis/goverter/cmd/goverter ./generated type Event struct { Name string Value int } // @goverter: ignore type EventConverter interface { Convert(source Event) Event } ``` -------------------------------- ### Input and Generated Code for arg:context:regex Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/arg.md Demonstrates the input Go code and the corresponding generated code when using the 'arg:context:regex' setting. ```go package context // Input is a placeholder for the input struct. type Input struct { Name string } // Output is a placeholder for the output struct. type Output struct { Context string } // Convert converts Input to Output. //goverter:transfer func Convert(input Input) Output { panic("implement me") } ``` ```go // Code generated by goverter --- DO NOT EDIT. package context // Convert converts Input to Output. func Convert(input Input) Output { return Output{ Context: input.Name, } } ``` -------------------------------- ### Generated Converter Implementation Source: https://context7.com/jmattheis/goverter/llms.txt This is an example of a generated Go struct (`ConverterImpl`) that implements the `Converter` interface. It handles slice conversion by iterating and calling a private conversion method. ```go // generated/generated.go (auto-generated, DO NOT EDIT) //go:build !goverter package generated import example "goverter/example" type ConverterImpl struct{} func (c *ConverterImpl) Convert(source []example.Input) []example.Output { var exampleOutputList []example.Output if source != nil { exampleOutputList = make([]example.Output, len(source)) for i := 0; i < len(source); i++ { exampleOutputList[i] = c.convertExampleInputToExampleOutput(source[i]) } } return exampleOutputList } ``` -------------------------------- ### Generated Go Code for ignoreMissing Example Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/ignoreMissing.md This Go code is generated by Goverter and shows how the ignoreMissing setting affects the conversion process when fields are missing in the target struct. ```go // Code generated by goverter --- DO NOT EDIT. package generated import bespoketype "../bespoketype" // Source is a type Source struct { Value1 string Value2 string Value3 string } // Target is a type Target struct { Value1 string Value3 string } // Convert is a func Convert(s Source) Target { return Target{ Value1: s.Value1, Value3: s.Value3, } } ``` -------------------------------- ### Go Function Signature with Named Params/Results Source: https://github.com/jmattheis/goverter/blob/main/docs/reference/signature.md Demonstrates how to use named parameters and results in a Go function signature. ```go type Converter interface { Convert(nameA A, nameB B) (nameC C, nameD D) } ``` -------------------------------- ### Define Mapping for `any` to `any` Conversion in Go Source: https://github.com/jmattheis/goverter/blob/main/docs/faq.md When Goverter encounters `any` to `any` or `interface{}` to `interface{}` type mismatches, you must explicitly define the mapping. This example shows how to pass the value without conversion. ```go package main type Input struct { Value any } type Output struct { Value any } //go:generate goverter -type MyConverter -output generated/generated.go . type MyConverter interface { Convert(Input) Output } ``` ```go package main // generated by goverter type generatedMyConverter struct { } // Convert implements MyConverter. // The Convert method is generated by goverter. func (s generatedMyConverter) Convert(inp Input) Output { return Output{ Value: inp.Value, // This is the explicit mapping for any to any } } ```