Explorar el Código

Improve HTTPServer validation

Stan hace 18 horas
padre
commit
02edd07ceb
Se han modificado 1 ficheros con 41 adiciones y 23 borrados
  1. 41 23
      http_server.go

+ 41 - 23
http_server.go

@@ -182,29 +182,10 @@ func (this *HTTPServer) ServeHTTP(responseStream http.ResponseWriter, requestStr
 			return
 		}
 
-		// TODO: improve
-		if handler.Validators != nil {
-			value := reflect.ValueOf(handler.Data)
-			for field := range value.Fields() {
-				validators, ok := handler.Validators[field.Name]
-				if !ok {
-					continue
-				}
-
-				if len(validators) == 0 {
-					continue
-				}
-
-				for _, validator := range validators {
-					if validator.Validate(value.Interface()) {
-						continue
-					}
-
-					this.log.Error("malformed validation failed", LogValue("path", requestStream.URL.Path), LogError(err))
-					responseStream.WriteHeader(http.StatusNotAcceptable)
-					return
-				}
-			}
+		if !validateData(handler) {
+			this.log.Error("malformed validation failed", LogValue("path", requestStream.URL.Path), LogError(err))
+			responseStream.WriteHeader(http.StatusNotAcceptable)
+			return
 		}
 	}
 
@@ -310,3 +291,40 @@ func copyStruct(dst interface{}, src interface{}) {
 		}
 	}
 }
+
+func validateData(handler HTTPServerHandler) bool {
+	if handler.Validators == nil {
+		return true
+	}
+
+	value := reflect.ValueOf(handler.Data)
+	if value.Kind() != reflect.Pointer {
+		return true
+	}
+
+	value = value.Elem()
+	if value.Kind() != reflect.Struct {
+		return true
+	}
+
+	for field := range value.Fields() {
+		validators, ok := handler.Validators[field.Name]
+		if !ok {
+			continue
+		}
+
+		if len(validators) == 0 {
+			continue
+		}
+
+		for _, validator := range validators {
+			if validator.Validate(value.Interface()) {
+				continue
+			}
+
+			return false
+		}
+	}
+
+	return true
+}