Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Decode ¶
Decode is a convenience wrapper around Unmarshal for standard HTTP handlers. It extracts the query parameters directly from the *http.Request URL and parses them into the provided struct pointer.
Example:
func SearchHandler(w http.ResponseWriter, r *http.Request) {
var filter SearchFilter
if err := qtag.Decode(r, &filter); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// ... use filter ...
}
func Unmarshal ¶
Unmarshal parses URL query parameters into a struct using reflection. It requires a valid pointer to a struct.
Behavior & Tag Routing ¶
- Basic Mapping: Define a `qt:"name"` tag to map a query parameter to a struct field.
- Default Values: Add `,default=value` to provide a fallback if the parameter is missing from the URL. Example: `qt:"limit,default=20"`.
- Ignored Fields: Use `qt:"-"` to explicitly tell the parser to skip a field entirely.
- Tagged Nested Structs: If a struct field has a `qt` tag, it acts as a namespace using dot-notation. Example: `qt:"user"` creates keys like `?user.name=Alice`.
- Untagged Nested Structs: If an embedded or nested struct has NO `qt` tag (or `qt:""`), its fields are "flattened" and inherit the parent's namespace.
Supported Types ¶
- Standard Types: string, bool, int/8/16/32/64, float32/64.
- Custom Types: Any type that implements encoding.TextUnmarshaler is automatically supported. This includes standard library types like time.Time (which expects RFC 3339).
Common Pitfalls ¶
- Passing by Value: You MUST pass a pointer to the struct (e.g., &myStruct), otherwise the function will return an error.
- Unexported Fields: Fields starting with a lowercase letter cannot be set via reflection and are silently skipped.
- Struct Initialization: If you pre-populate your struct with values before calling Unmarshal, and a query parameter is missing, qtag will leave your pre-populated value alone unless you defined a default tag, which will overwrite it.
Example:
type Pagination struct {
Limit int `qt:"limit,default=20"`
Page int `qt:"page,default=1"`
}
type SearchQuery struct {
Pagination // Untagged: inherits keys flatly (?limit=50)
User UserFilter `qt:"user"` // Tagged: uses dot-notation (?user.name=Alice)
InternalID string `qt:"-"`
}
values, _ := url.ParseQuery("limit=50&user.name=Alice")
var q SearchQuery
err := qtag.Unmarshal(values, &q)
Types ¶
type TagOptions ¶
Click to show internal directories.
Click to hide internal directories.