Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you validate HTTP request inputs in Go without a framework?
Input validation is a layered concern: structural validation (is the JSON well-formed?), field validation (are required fields present, within range?), and business validation (does the email already exist?). Go handles this without a framework using explicit checks and helper functions.
// Request and validation error types type CreateUserRequest struct { Name string `json:"name"` Email string `json:"email"` Age int `json:"age"` } type ValidationErrors map[string]string func (ve ValidationErrors) Error() string { msgs := make([]string, 0, len(ve)) for k, v := range ve { msgs = append(msgs, k+": "+v) } return strings.Join(msgs, ", ") } // Validator function func validateCreateUser(req CreateUserRequest) error { errs := ValidationErrors{} if strings.TrimSpace(req.Name) == "" { errs["name"] = "is required" } else if len(req.Name) > 100 { errs["name"] = "must be 100 characters or fewer" } if req.Email == "" { errs["email"] = "is required" } else if !isValidEmail(req.Email) { errs["email"] = "is not a valid email address" } if req.Age < 0 || req.Age > 150 { errs["age"] = "must be between 0 and 150" } if len(errs) > 0 { return errs } return nil } // Handler func createUserHandler(w http.ResponseWriter, r *http.Request) error { var req CreateUserRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return &APIError{Status: 400, Code: "INVALID_JSON", Message: "request body must be valid JSON"} } if err := validateCreateUser(req); err != nil { var ve ValidationErrors if errors.As(err, &ve) { writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"errors": ve}) return nil } return err } user, err := userService.Create(r.Context(), req) if err != nil { return err } return writeJSON(w, http.StatusCreated, user) }
More Related questions...