Skip to content

Instantly share code, notes, and snippets.

@scottcagno
Created January 30, 2023 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottcagno/ad4de8e2e45b7f34b80d4dd9c36b353f to your computer and use it in GitHub Desktop.
Save scottcagno/ad4de8e2e45b7f34b80d4dd9c36b353f to your computer and use it in GitHub Desktop.
General purpose DTO in Go
package main
import (
"fmt"
"reflect"
)
type User struct {
ID int
Name string
Email string
IsActive bool
}
var user = User{1, "Jon Doe", "jdoe@example.com", 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