Skip to main content

form

form is a directive executor who decodes a field from HTTP form data, i.e. http.Request.Form.

Definition

Name: "form"
Args: KEY1 [,KEY2 [,KEY3, ...]]

form will examine values of the keys one by one (KEY1 -> KEY2 -> ...) from the form data, the first non-empty value will be used to set the corresponding field of the input struct.

caution

In most cases, the form directive just works like query. Because it also visits data from the URL querystring. But if the form data sent by the client was of application/x-www-form-urlencoded content type, form will visit the form data first, and then visit the URL querystring.

For more details, please refer to GH-5 add a query directive to pull values from querystring params #6 and the following quotes.

From the Go documentation:

Form contains the parsed form data, including both the URL field's query parameters and the PATCH, POST, or PUT form data. This field is only available after ParseForm is called.

And for http.Request.ParseForm, it is:

ParseForm populates r.Form and r.PostForm. For all requests, ParseForm parses the raw query from the URL and updates r.Form. For POST, PUT, and PATCH requests, it also reads the request body, parses it as a form and puts the results into both r.PostForm and r.Form. Request body parameters take precedence over URL query string values in r.Form.

Usage

type Profile struct {
Role string `in:"form=role"`
Hireable bool `in:"form=hireable"`
}
Request (Mixed, Body + URL query)Profile
GET /users?role=backend&hireable=true
{
Role: "backend",
Hireable: true,
}

// works just like query directive
POST /users HTTP/1.1
Host: foo.example
Content-Type: application/x-www-form-urlencoded

role=frontend&hireable=false
{
Role: "frontend",
Hireable: false,
}
POST /users?hireable=true HTTP/1.1
Host: foo.example
Content-Type: application/x-www-form-urlencoded

role=frontend&hireable=false
{
Role: "frontend",
Hireable: false,
}

// Hireable in the body overrides the URL query.
POST /users?hireable=true HTTP/1.1
Host: foo.example
Content-Type: application/x-www-form-urlencoded

role=frontend
{
Role: "frontend",
Hireable: true,
}

// Hireable is from URL query.