builder

package module
v0.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 12 Imported by: 1 module, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Expression Builder 🔨

Go Reference Version Build Status Go Report Card Codecov

Safe queries from URL query strings

Expression Builder works with the exp expression library to define templates that are safely populated with data from a URL query string.


func Handler(r *http.Request, w http.ResponseWriter) {

	// Define the URL arguments you want to allow and their types
	b := NewBuilder().
		String("firstName").
		String("lastName").
		Int("publishDate").
		Bool("isPublished")

	// Create a usable expression from the URL query string
	expression := b.Evaluate(r.URL.Query())

	// Next, safely pass it into the database, or something...
}

Operators

By default each parameter is compared with =. A query value may override this with an OP:value prefix, where OP is one of the operator aliases recognized by exp (EQ, NE, GT, GTE, LT, LTE, CONTAINS, BEGINS, case-insensitive):

?publishDate=gt:1000      // publishDate >  1000
?firstName=ne:John        // firstName  != "John"
?lastName=BEGINS:Mc       // lastName begins with "Mc"

A field's default operator can also be set in code with WithDefaultOperator (and the WithDefaultOp* shortcuts). Repeating a parameter (?firstName=a&firstName=b) combines the values with OR; distinct parameters combine with AND.

Time Ranges

A Time parameter accepts a timestamp, or the name of a relative range that expands to a half-open [begin, end) pair anchored to midnight UTC:

?date=today          ?date=yesterday      ?date=tomorrow
?date=this-week      ?date=next-week
?date=last-month     ?date=this-month     ?date=next-month
?date=last-year      ?date=this-year      ?date=next-year
?date=past-30-days   ?date=next-90-days   ...and the other 30/60/90/180/365 variants

What Doesn't Reach the Database

Anything you didn't ask for. A parameter that was never registered on the Builder is ignored, and a value that won't parse as its declared data type is dropped.

An empty value is kept, because it is a real comparison — (field == "") || (field == "VALUE") is how you ask for "unset, or this". Be aware of what that means when you attach a WithFilter: if your filter can return an empty string, the comparison becomes an empty one, and with CONTAINS that matches every record.

That guarantee covers the shape of the query, not who is allowed to run it. Combine the result with your own access rules:

criteria := exp.And(
	b.Evaluate(r.URL.Query()),
	exp.Equal("ownerId", currentUser.ID),
)

Pull Requests Welcome

This library is a work in progress, and will benefit from your experience reports, use cases, and contributions. If you have an idea for making this library better, send in a pull request. We're all in this together! 🔨

Documentation

Overview

Package builder turns a URL query string into a database expression, using an allow-list of parameters that the caller declares up front.

A Builder maps each permitted URL parameter to a data type, and Evaluate reads a url.Values against it:

b := builder.NewBuilder().
	String("firstName").
	Int("publishDate").
	Bool("isPublished")

criteria := b.Evaluate(request.URL.Query())

The result is an exp.Expression, ready to hand to a query. Repeating a parameter combines its values with OR; distinct parameters combine with AND.

Only declared parameters reach the expression

This is the safety guarantee, and the reason to use this package rather than reading query parameters by hand. A parameter that was never declared on the Builder is ignored, and a value that cannot be parsed as its declared data type is dropped. Neither one is an error, and neither one reaches the database.

An empty value, on the other hand, is a real comparison and is kept: a field that may be unset is queried as (field == "") OR (field == "VALUE"). Note the consequence for a Field that carries a WithFilter -- if the filter empties the value, the comparison becomes an empty one, and with CONTAINS that matches every record. Filters that can return "" deserve a second look.

The guarantee covers SHAPE, not authorization. A caller is still responsible for restricting the query to records the visitor may see -- typically by combining the result with exp.And.

Operator prefixes

Each parameter is compared with "=" by default, which WithDefaultOperator (and its WithDefaultOp shortcuts) can change per field. A query string may also name its own operator with an "OP:value" prefix, using any of the operator aliases that exp recognizes:

?publishDate=gt:1000      publishDate >  1000
?firstName=ne:John        firstName  != "John"
?lastName=BEGINS:Mc       lastName begins with "Mc"

Only the FIRST colon splits the prefix from the value, so "eq:a:b:c" compares against "a:b:c". An unrecognized prefix is not an error -- the field's default operator is used, and the whole string, prefix included, becomes the value. That is what lets a timestamp such as "2026-01-01T09:30:00Z" pass through unharmed.

Two data types define their own comparison and therefore discard the operator: a Polygon always emits GEO-WITHIN, and a Time whose value names a range (see below) always emits the half-open pair that bounds it. Both still strip the prefix before parsing the value.

Time ranges

A Time parameter accepts a timestamp, or the name of a relative range, which expands to a half-open [begin, end) pair anchored to midnight UTC:

today          yesterday      tomorrow
this-week      next-week
last-month     this-month     next-month
last-year      this-year      next-year
past-30-days   past-60-days   past-90-days   past-180-days   past-365-days
next-30-days   next-60-days   next-90-days   next-180-days   next-365-days

Evaluate and EvaluateAll

Evaluate uses whichever declared parameters are present. EvaluateAll requires every declared parameter to be present and non-empty, and returns a derp.BadRequest naming the first one that is missing.

Index

Constants

View Source
const DataTypeBool = "BOOL"

DataTypeBool represents a boolean parameter

View Source
const DataTypeInt = "INT"

DataTypeInt represents an integer parameter

View Source
const DataTypeInt64 = "INT64"

DataTypeInt64 represents a 64-bit integer parameter

View Source
const DataTypeObjectID = "OBJECTID"

DataTypeObjectID represents a mongodb "ObjectId" parameter (24-byte hex string)

View Source
const DataTypePolygon = "POLYGON"

DataTypePolygon represents a GeoJSON polygon

View Source
const DataTypeString = "STRING"

DataTypeString represents a string parameter

View Source
const DataTypeTime = "TIME"

DataTypeTime represents a time.Time parameter

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

type Builder map[string]Field

Builder maps URL parameter names to the Fields that describe how to turn their values into an expression.

func NewBuilder

func NewBuilder() Builder

NewBuilder returns an empty Builder.

func (Builder) Bool

func (b Builder) Bool(name string, options ...FieldOption) Builder

Bool adds a boolean-based parameter to the expression Builder

func (Builder) Evaluate

func (b Builder) Evaluate(values url.Values) exp.Expression

Evaluate returns an Expression built from the url.Values provided, using only the parameters that this Builder declares. Everything else is ignored.

func (Builder) EvaluateAll added in v0.5.0

func (b Builder) EvaluateAll(values url.Values) (exp.Expression, error)

EvaluateAll is like Evaluate, but every field defined in the Builder must be present and non-empty in the URL values. It returns an error if any is missing.

func (Builder) EvaluateField added in v0.7.0

func (b Builder) EvaluateField(field Field, values []string) exp.Expression

EvaluateField converts the raw URL values for a single field into an expression, parsing each value according to the field's data type.

func (Builder) HasURLParams added in v0.5.0

func (b Builder) HasURLParams(values url.Values) bool

HasURLParams returns TRUE if the URL contains any parameters that match the Builder. It tests only for the parameter's presence, so a blank or unparseable value still counts here while Evaluate would discard it.

func (Builder) Int

func (b Builder) Int(name string, options ...FieldOption) Builder

Int adds an integer-based parameter to the expression Builder

func (Builder) Int64 added in v0.7.0

func (b Builder) Int64(name string, options ...FieldOption) Builder

Int64 adds a 64-bit integer-based parameter to the expression Builder

func (Builder) ObjectID

func (b Builder) ObjectID(name string, options ...FieldOption) Builder

ObjectID adds a mongodb ObjectID-based parameter to the expression Builder

func (Builder) Polygon added in v0.10.7

func (b Builder) Polygon(name string, options ...FieldOption) Builder

Polygon adds a GeoJSON polygon-based parameter to the expression Builder

func (Builder) String

func (b Builder) String(name string, options ...FieldOption) Builder

String adds a string-based parameter to the expression Builder

func (Builder) Time added in v0.10.0

func (b Builder) Time(name string, options ...FieldOption) Builder

Time adds a time-based parameter to the expression Builder

type Field added in v0.7.7

type Field struct {
	Name     string
	DataType string
	Operator string
	Filters  []Filter
}

Field describes a single queryable parameter: the expression field name, its data type, the default comparison operator, and any input filters.

func NewField added in v0.7.7

func NewField(name string, dataType string, options ...FieldOption) Field

NewField returns a Field for the given name and data type, applying any options in order.

type FieldOption added in v0.7.7

type FieldOption func(*Field)

FieldOption is a function that configures a Field during construction.

func WithAlias added in v0.7.7

func WithAlias(name string) FieldOption

WithAlias defines the field name to use when creating an expression, which may be different from the field name to read from the URL.

func WithDefaultOpBeginsWith added in v0.8.3

func WithDefaultOpBeginsWith() FieldOption

WithDefaultOpBeginsWith defines "BEGINS" as the default operator to use when creating an expression.

func WithDefaultOpContains added in v0.7.7

func WithDefaultOpContains() FieldOption

WithDefaultOpContains defines "CONTAINS" as the default operator to use when creating an expression.

func WithDefaultOpEqual added in v0.7.7

func WithDefaultOpEqual() FieldOption

WithDefaultOpEqual defines "EQUAL" as the default operator to use when creating an expression.

func WithDefaultOperator added in v0.7.7

func WithDefaultOperator(operator string) FieldOption

WithDefaultOperator defines the default operator to use when creating an expression

func WithFilter added in v0.9.0

func WithFilter(filter Filter) FieldOption

WithFilter adds a filter that transforms each input value before it is converted to the field's data type and compared.

type Filter added in v0.9.0

type Filter func(string) string

Filter transforms an input string before it is converted and compared.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址