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)
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
