I’m building my web framework in Go to make it feel more like the way NestJS handles JSON validation and sends HTTP error messages. Currently, I’m facing a challenge regarding how to determine if a field in a struct type is not provided. I don’t mean checking if the value is an empty string or a zero value, like using reflect.Value.IsZero() or reflect.Value.IsValid(). I want to know if there is a way to check if a struct has a field that is nil.
Example:
type User struct{
Name string `json:"name" validator:"optional"`
Value string `json:"value" validator:"required"`
}
var data User
json.Unmarshal(body, &data) //name was not provided in the request so it should not be checked
errValidacao, hasError := validator.CheckPropretys[User](data)
func CheckProperties[T any](data T) (string, bool) {
t := reflect.TypeOf(data)
v := reflect.ValueOf(data)
errorMessage := ""
hasError := false
if t.Kind() == reflect.Map {
return "", hasError
}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
value := v.Field(i)
typeValidation := field.Tag.Get("validator")
if typeValidation == "" {
continue
}
toValidate := util.CommonToArray(typeValidation) // Returns an array with options to validate
firstErr := true
hasOptionalField := findOptional(toValidate)
if hasOptionalField && value.IsValid() && !value.IsZero() {
continue
}
currentErrMessage := ""
for j := 0; j < len(toValidate); j++ {
test := string(testCase(toValidate[j], value, field))
if firstErr && test != "" {
currentErrMessage += test
hasError = true
} else if test != "" {
currentErrMessage += "," + test
hasError = true
}
}
if errorMessage != "" && currentErrMessage != "" {
errorMessage += ";"
hasError = true
}
if currentErrMessage != "" {
nameCamp := field.Tag.Get("json")
if nameCamp == "" {
nameCamp = field.Tag.Get("query")
}
errorMessage += nameCamp + ":" + currentErrMessage
hasError = true
}
}
return errorMessage, hasError
}
I have tried using every single function in the reflector package, i have not suceded, even json omitEmpty did not bring any results
user27403331 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1