My background is python/django so in python we have serializer to decide which field should be proccessed from request body and which field should be return in response body
I can’t find something like this in golang/gin/gorm
and I see their are many people doesn’t recommend DTO (data transfer object).
so is their library or prefered pattern in go to serializer & deserialize data ?
cases:
if I have endpoint /user/:id/update/
I want to ignore password field even if user sent it.
if I have endpoint /user to list all user
I didn’t want to add password field in response.
try 1: I tired to use json:"-"
but i think it’s not prefect because I will have another endpoint to update user password
try 2 :
I created generic function to set value of specific fields to null and add omitempty to all fields
I’m not sure it’s prefect solution or not
func ToStruct[T any](s T, flds []string) T {
elem := reflect.ValueOf(s).Elem()
for i:=0; i<elem.NumField(); i++ {
if slices.Contains(flds, elem.Type().Field(i).Name) {
f := elem.Field(i)
if f.Kind() == reflect.Ptr {
// Set the field value to nil
f.Set(reflect.Zero(f.Type()))
} else {
// Set the field value to its zero value}
f.SetZero()
}
}
}
return s
}