urit

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2023 License: Apache-2.0 Imports: 13 Imported by: 3

README

Urit

GoDoc Latest Version codecov Go Report Card

Overview

Go package for templated URIs - enables building URIs from templates and extracting path vars from templates

Define path vars by name...

template := urit.MustCreateTemplate(`/foo/{foo-id:[a-z]*}/bar/{bar-id:[0-9]*}`)
pth, _ := template.PathFrom(urit.Named(
    "foo-id", "abc",
    "bar-id", "123"))
println(pth)

or positional...

template := urit.MustCreateTemplate(`/foo/?/bar/?`)
pth, _ := template.PathFrom(urit.Positional("abc", "123"))
println(pth)

Extract vars from paths - using named...

template := urit.MustCreateTemplate(`/credits/{year:[0-9]{4}}/{month:[0-9]{2}}`)
req, _ := http.NewRequest(`GET`, `http://www.example.com/credits/2022/11`, nil)
vars, ok := template.MatchesRequest(req)
println(ok)
println(vars.Get("year"))
println(vars.Get("month"))

Or extract using positional...

template := urit.MustCreateTemplate(`/credits/?/?`)
req, _ := http.NewRequest(`GET`, `http://www.example.com/credits/2022/11`, nil)
vars, ok := template.MatchesRequest(req)
println(ok)
println(vars.Get(0))
println(vars.Get(1))

Generate path from a template...

template := urit.MustCreateTemplate(`/credits/{year:[0-9]{4}}/{month:[0-9]{2}}`)

path, _ := template.PathFrom(urit.Named("year", "2022", "month", "11"))
println(path)

Installation

To install Urit, use go get:

go get github.com/go-andiamo/urit

To update Urit to the latest version, run:

go get -u github.com/go-andiamo/urit

Documentation

Overview

Package urit - Go package for building URIs from templates and extracting path vars from URIs (using template)

Define path vars by name...

template := urit.MustCreateTemplate(`/foo/{foo-id:[a-z]*}/bar/{bar-id:[0-9]*}`)
pth, _ := template.PathFrom(urit.Named(
	"foo-id", "abc",
	"bar-id", "123"))
println(pth)

or positional...

template := urit.MustCreateTemplate(`/foo/?/bar/?`)
pth, _ := template.PathFrom(urit.Positional("abc", "123"))
println(pth)

Extract vars from paths - using named...

template := urit.MustCreateTemplate(`/credits/{year:[0-9]{4}}/{month:[0-9]{2}}`)
req, _ := http.NewRequest(`GET`, `http://www.example.com/credits/2022/11`, nil)
vars, ok := template.MatchesRequest(req)
println(ok)
println(vars.Get("year"))
println(vars.Get("month"))

Or extract using positional...

template := urit.MustCreateTemplate(`/credits/?/?`)
req, _ := http.NewRequest(`GET`, `http://www.example.com/credits/2022/11`, nil)
vars, ok := template.MatchesRequest(req)
println(ok)
println(vars.Get(0))
println(vars.Get(1))

Index

Constants

This section is empty.

Variables

View Source
var (
	CaseInsensitiveFixed = _CaseInsensitiveFixed // is a FixedMatchOption that can be used with templates to allow case-insensitive fixed path parts
	PathRegexCheck       = _PathRegexCheck       // is a VarMatchOption that can be used with Template.PathFrom or Template.RequestFrom to check that vars passed in match regexes for the path part
)

Functions

This section is empty.

Types

type FixedMatchOption

type FixedMatchOption interface {
	Match(value string, expected string, pathPos int, vars PathVars) bool
}

FixedMatchOption is the option interface for checking if a fixed path part matches the template

An example is provided by the CaseInsensitiveFixed - which allows fixed path parts to be matched regardless of case

type Headers added in v1.1.0

type Headers interface {
	HeadersOption
	Set(key string, value interface{}) Headers
	Get(key string) (interface{}, bool)
	Has(key string) bool
	Del(key string) Headers
	Clone() Headers
}

func NewHeaders added in v1.1.0

func NewHeaders(namesAndValues ...interface{}) (Headers, error)

type HeadersOption added in v1.1.0

type HeadersOption interface {
	GetHeaders() (map[string]string, error)
}

type Host added in v1.1.0

type Host interface {
	HostOption
}

func NewHost added in v1.1.0

func NewHost(address string) Host

type HostOption added in v1.1.0

type HostOption interface {
	GetAddress() string
}

type PathVar

type PathVar struct {
	Name          string
	NamedPosition int
	Position      int
	Value         interface{}
}

type PathVars

type PathVars interface {
	GetPositional(position int) (string, bool)
	GetNamed(name string, position int) (string, bool)
	GetNamedFirst(name string) (string, bool)
	GetNamedLast(name string) (string, bool)
	Get(idents ...interface{}) (string, bool)
	GetAll() []PathVar
	Len() int
	Clear()
	// VarsType returns the path vars type (Positions or Names)
	VarsType() PathVarsType
	AddNamedValue(name string, val interface{}) error
	AddPositionalValue(val interface{}) error
}

PathVars is the interface used to pass path vars into a template and returned from a template after extracting

Use either Positional or Named to create a new PathVars

func Named

func Named(namesAndValues ...interface{}) PathVars

Named creates a named PathVars from the name and value pairs supplied

Notes:

* If there is not a value for each name - this function panics (so ensure that the number of varargs passed is an even number!)

* If any of the name values are not a string - this function panics

func PathVarsFromMap added in v1.2.0

func PathVarsFromMap(m map[string]interface{}) PathVars

func Positional

func Positional(values ...interface{}) PathVars

Positional creates a positional PathVars from the values supplied

type PathVarsType

type PathVarsType int
const (
	Positions PathVarsType = iota
	Names
)

type QueryParams added in v1.1.0

type QueryParams interface {
	QueryParamsOption
	Get(key string) (interface{}, bool)
	GetIndex(key string, index int) (interface{}, bool)
	Set(key string, value interface{}) QueryParams
	Add(key string, value interface{}) QueryParams
	Del(key string) QueryParams
	Has(key string) bool
	Sorted(on bool) QueryParams
	Clone() QueryParams
}

func NewQueryParams added in v1.1.0

func NewQueryParams(namesAndValues ...interface{}) (QueryParams, error)

type QueryParamsOption added in v1.1.0

type QueryParamsOption interface {
	GetQuery() (string, error)
}

type Stringable added in v1.1.0

type Stringable interface {
	String() string
}

type Template

type Template interface {
	// PathFrom generates a path from the template given the specified path vars
	PathFrom(vars PathVars, options ...interface{}) (string, error)
	// RequestFrom generates a http.Request from the template given the specified path vars
	RequestFrom(method string, vars PathVars, body io.Reader, options ...interface{}) (*http.Request, error)
	// Matches checks whether the specified path matches the template -
	// and if a successful match, returns the extracted path vars
	Matches(path string, options ...interface{}) (PathVars, bool)
	// MatchesUrl checks whether the specified URL path matches the template -
	// and if successful match, returns the extracted path vars
	MatchesUrl(u url.URL, options ...interface{}) (PathVars, bool)
	// MatchesRequest checks whether the specified request matches the template -
	// and if a successful match, returns the extracted path vars
	MatchesRequest(req *http.Request, options ...interface{}) (PathVars, bool)
	// Sub generates a new template with added sub-path
	Sub(path string, options ...interface{}) (Template, error)
	// ResolveTo generates a new template, filling in any known path vars from the supplied vars
	ResolveTo(vars PathVars) (Template, error)
	// VarsType returns the path vars type (Positions or Names)
	VarsType() PathVarsType
	// Vars returns the path vars of the template
	Vars() []PathVar
	// OriginalTemplate returns the original (or generated) path template string
	OriginalTemplate() string
	// Template returns the template (optionally with any path var patterns removed)
	Template(removePatterns bool) string
}

Template is the interface for a URI template

func MustCreateTemplate

func MustCreateTemplate(path string, options ...interface{}) Template

MustCreateTemplate is the same as NewTemplate, except that it panics on error

func NewTemplate

func NewTemplate(path string, options ...interface{}) (Template, error)

NewTemplate creates a new URI template from the path provided

returns an error if the path cannot be parsed into a template

The options can be any FixedMatchOption or VarMatchOption - which can be used to extend or check fixed or variable path parts

type TemplateParseError

type TemplateParseError interface {
	error
	Unwrap() error
	Position() int
}

type VarMatchOption

type VarMatchOption interface {
	Applicable(value string, position int, name string, rx *regexp.Regexp, rxs string, pathPos int, vars PathVars) bool
	Match(value string, position int, name string, rx *regexp.Regexp, rxs string, pathPos int, vars PathVars) (string, bool)
}

VarMatchOption is the option interface for checking if a variable part matches the template

It can also be used to adjust the path variable found

Jump to

Keyboard shortcuts

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