func handleFormPost(w http.ResponseWriter, r *http.Request) { err := r.ParseForm() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } name := r.Form.Get("name") email := r.Form.Get("email") // Do something with the form data... }
func formParseMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { err := r.ParseForm() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Store the form data in a context value ctx := context.WithValue(r.Context(), "form", r.Form) // Call the next handler with the updated request context next.ServeHTTP(w, r.WithContext(ctx)) }) } func handleFormGet(w http.ResponseWriter, r *http.Request) { // Retrieve the form data from the context value form := r.Context().Value("form").(url.Values) name := form.Get("name") email := form.Get("email") // Do something with the form data... } func main() { http.Handle("/form", formParseMiddleware(http.HandlerFunc(handleFormGet))) http.ListenAndServe(":8080", nil) }In this example, we define a middleware handler that parses form data using ParseForm and stores it in a context value. We then use this middleware in a GET request handler to retrieve the form data from the context value. Overall, the http.Request.ParseForm method is a useful feature in the standard net/http library for parsing form data in HTTP requests.