Help us shape the future of Go! Take the 2026 Go Developer Survey

pathvars

package module
v0.0.16 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2024 License: MIT Imports: 3 Imported by: 7

README

Extractor

Extracts path variables from URLs.

Example Usage

package main

import (
	"fmt"
	"net/http"

	"github.com/a-h/pathvars"
)

var matcher = pathvars.NewExtractor("/user/{userid}")

func main() {
	r, _ := http.NewRequest("GET", "/user/123", nil)
	values, ok := matcher.Extract(r.URL)
	fmt.Println("OK:", ok)
	fmt.Println("User ID:", values["userid"])
}

Example Output

$ go run main.go
OK: true
User ID: 123

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Extractor

type Extractor struct {
	Routes []*Route
}

Extractor checks routes to see if any can be matched, and what path variables are in them.

func NewExtractor

func NewExtractor(patterns ...string) *Extractor

NewExtractor creates an extractor.

func (*Extractor) Extract

func (pm *Extractor) Extract(u *url.URL) (v map[string]string, ok bool)

Extract variables from the path.

func (*Extractor) ExtractString

func (pm *Extractor) ExtractString(s string) (v map[string]string, ok bool)

ExtractString extracts path variables from a string.

type Route

type Route []*Segment

Route is an array of segments.

func NewRoute

func NewRoute(pattern string) *Route

NewRoute creates a route based on a pattern, e.g /users/{userid}.

func (Route) Match

func (r Route) Match(segments []string) (vars map[string]string, ok bool)

Match returns whether the route was matched, and extracts variables.

type Segment

type Segment struct {
	Name       string
	IsVariable bool
	IsWildcard bool
}

Segment is a path segment, e.g. in /users/{userid}/ there are two segments, "users" and "{userid}". "{userid}" is a variable and will be captured.

func (*Segment) Match

func (ps *Segment) Match(s string) (name string, capture bool, wildcard bool, matches bool)

Match on the string path segment.

func (*Segment) String

func (ps *Segment) String() string

String pretty prints the segment, for debugging.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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