Created
January 30, 2023 18:56
-
-
Save scottcagno/ad4de8e2e45b7f34b80d4dd9c36b353f to your computer and use it in GitHub Desktop.
General purpose DTO in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
type User struct { | |
ID int | |
Name string | |
Email string | |
IsActive bool | |
} | |
var user = User{1, "Jon Doe", "[email protected]", true} | |
func main() { | |
tbl := NewTableDTO(&user) | |
fmt.Println(tbl) | |
} | |
type FieldDTO struct { | |
Field reflect.StructField | |
Value reflect.Value | |
} | |
type TableDTO struct { | |
Type reflect.Type | |
Fields []FieldDTO | |
} | |
func NewTableDTO(v any) *TableDTO { | |
t := &TableDTO{ | |
Type: reflect.Indirect(reflect.ValueOf(v)).Type(), | |
Fields: make([]FieldDTO, 0), | |
} | |
ParseStruct(v, func(f reflect.StructField, v reflect.Value) { | |
t.Fields = append(t.Fields, FieldDTO{ | |
Field: f, | |
Value: v, | |
}) | |
}) | |
return t | |
} | |
func ParseStruct(v any, fn func(reflect.StructField, reflect.Value)) { | |
val := reflect.Indirect(reflect.ValueOf(v)) | |
for i := 0; i < val.NumField(); i++ { | |
fn(val.Type().Field(i), val.Field(i)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment