pat (formerly pat.go) - A Sinatra style pattern muxer for Go's net/http library

pat (formerly pat.go) - A Sinatra style pattern muxer for Go's net/http library

GoDoc

INSTALL

$ go get github.com/bmizerany/pat

USE

package main

import (
	"io"
	"net/http"
	"github.com/bmizerany/pat"
	"log"
)

// hello world, the web server
func HelloServer(w http.ResponseWriter, req *http.Request) {
	io.WriteString(w, "hello, "+req.URL.Query().Get(":name")+"!\n")
}

func main() {
	m := pat.New()
	m.Get("/hello/:name", http.HandlerFunc(HelloServer))

	// Register this pat with the default serve mux so that other packages
	// may also be exported. (i.e. /debug/pprof/*)
	http.Handle("/", m)
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

It's that simple.

For more information, see: http://godoc.org/github.com/bmizerany/pat

CONTRIBUTORS

  • Alexis Svinartchouk (@zvin)
  • Blake Mizerany (@bmizerany)
  • Brian Ketelsen (@bketelsen)
  • Bryan Matsuo (@bmatsuo)
  • Caleb Spare (@cespare)
  • Evan Shaw (@edsrzf)
  • Gary Burd (@garyburd)
  • George Rogers (@georgerogers42)
  • Keith Rarick (@kr)
  • Matt Williams (@mattyw)
  • Mike Stipicevic (@wickedchicken)
  • Nick Saika (@nesv)
  • Timothy Cyrus (@tcyrus)
  • binqin (@binku87)

LICENSE

Copyright (C) 2012 by Keith Rarick, Blake Mizerany

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Owner
Comments
  • created LICENSE file, content copy&pasted from README.md

    created LICENSE file, content copy&pasted from README.md

    We use this project in a big OSS project and use tooling to track the licenses of our many dependencies. Having the license text in a separate file called LICENSE helps us tremendously as the tool will be able to pick it up. Thanks!

  • Fix slash match everything

    Fix slash match everything

    We should merge this binku87 commit, it fixes a panic with m.Get("/", http.HandlerFunc(...)) handlers :

    2012/06/11 16:48:22 http: panic serving 127.0.0.1:36657: runtime error: index out of range /usr/lib/go/src/pkg/net/http/server.go:576 (0x447bba) _func_003: buf.Write(debug.Stack()) /build/buildd/golang-stable-1/src/pkg/runtime/proc.c:1443 (0x40fb00) /build/buildd/golang-stable-1/src/pkg/runtime/runtime.c:128 (0x4105cc) /build/buildd/golang-stable-1/src/pkg/runtime/runtime.c:85 (0x410473) /home/alexis/go/src/github.com/zvin/pat/mux.go:217 (0x42756d) com/zvin/pat.(_patHandler).try: if ph.pat[len(ph.pat)-1] == '/' { /home/alexis/go/src/github.com/zvin/pat/mux.go:118 (0x426cc3) com/zvin/pat.(_PatternServeMux).ServeHTTP: if _, ok := ph.try(r.URL.Path); ok { /usr/lib/go/src/pkg/net/http/server.go:924 (0x43ca95) (_ServeMux).ServeHTTP: mux.handler(r).ServeHTTP(w, r) /usr/lib/go/src/pkg/net/http/server.go:656 (0x43ba26) (_conn).serve: handler.ServeHTTP(w, w.req) /build/buildd/golang-stable-1/src/pkg/runtime/proc.c:271 (0x40dc06)

  • Add support for the HTTP PATCH method.

    Add support for the HTTP PATCH method.

    @cespare I messed something up big-time, and it's been a long day, so I just split the changes off into their own branch. They have been squashed, like you asked.

  • Tail() fix

    Tail() fix

    The Tail() function does not behave as godoc describes. I exhibited this with a test and then fixed the indexing errors on ~~that test case~~ (edit: those test cases).

  • Is this project still alive?

    Is this project still alive?

    I see that it hasn't been updated in a while. Is this project still maintained, or is just so solid that it's done until a future version of Go requires it to change?

  • question about the top path

    question about the top path

    i think the pattern /:name/ should match _localhost:12345/abc/_ and _localhost:12345/abc_

    according the example provided in the code:

    // Example pattern with one capture: // /hello/:name // Will match: // /hello/blake // /hello/keith // Will not match: // /hello/blake/ // /hello/blake/foo // /foo // /foo/bar // // Example 2: // /hello/:name/ // Will match: // /hello/blake/ // /hello/keith/foo // /hello/blake // /hello/keith // Will not match: // /foo // /foo/bar

    What do you think? But I found the behavior is not the same as I supposed.

    The fact is that, I wanna to the pattern /:name/ match _localhost:12345/abc_ but when i type the URL in Chrome, it will turn to _localhost:12345/:name_

    see the example

  • Use EscapedPath for URL handling

    Use EscapedPath for URL handling

    We encountered an issue where escaped slashes %2f were being unescaped and routed incorrectly.

    This change defers unescaping the path until the parameters are extracted, rather than before routing.

  • dockerized version

    dockerized version

    I've added a Dockerfile and changed the source code from the hello.go to be able to run using docker container.

    Also the http port can be passed as an env variable.

  • moved hello_appengine to new dir

    moved hello_appengine to new dir

    In the current example folder there are two packages

    package main: hello.go

    package patexample hello_appengine.go

    I've fixed this

    It's only a trivial change, I noticed it when running the static analysis in go1.3

  • Add support to save original pattern to context

    Add support to save original pattern to context

    Inspired by mux and other routers preserve the matched pattern that can be referenced in the lifetime of a handler. This is useful for telemetry and instrumentation to use the pattern AND not the whole URL, which can result in cardinality explosion. For compatibility with most other mux like gorilla, mux, use count=2

  • Add go.mod file for use with go modules

    Add go.mod file for use with go modules

    This will also require a version tag be added to the repo for it to work properly in a project's own go.mod files.

    (About the go version number: Ian explains it here. So it's safe to leave it as go mod init generated it.)

  • Use context to pass extracted parameters instead of query params

    Use context to pass extracted parameters instead of query params

    Now that net/http supports context, I think it will be more appropriate to pass the extracted parameters via context. This will avoid confusion regarding what are actual query parameters. Obviously doing this will break backward compatibility.

  • add Lookup and AllowedMethods methods, change custom NotFound semantics

    add Lookup and AllowedMethods methods, change custom NotFound semantics

    Hello,

    I've used something like this fork of pat for a while, it adds two methods that can be very useful when building middleware chains:

    • AllowedMethods : returns the allowed methods for a given path, useful esp. for a CORS middleware.
    • Lookup : returns the matching registered handler for a given method and path, useful if in a middleware you want to check if the request actually has a handler before starting setting up the usual chain (e.g. logging, panic recover, cors, etc.)

    I also made another change that may be a bit trickier to merge, I found it quite weird that setting a custom NotFound handler on the mux changed the way the 404 was returned. If there's no NotFound and a path has other methods registered, it returns a 405, and the 404 is only returned if there's no match and no other methods for the path. Once you set a custom NotFound handler, the behaviour changes and the 405 is not returned anymore (presumably it's because the custom not found should handle it? Still seems weird/unexpected).

    So this PR changes the behaviour so that setting a custom NotFound still behaves the same way as without it - it's just called if no 405 was returned. A case could probably be made to add support for a custom MethodNotAllowed handler, but I didn't add this.

    I'm fine with keeping this stuff in my fork if you're not interested in adding more API surface to the package, no worries.

    Thanks, Martin

Related tags
Go package to simulate bandwidth, latency and packet loss for net.PacketConn and net.Conn interfaces

lossy Go package to simulate bandwidth, latency and packet loss for net.PacketConn and net.Conn interfaces. Its main usage is to test robustness of ap

Oct 14, 2022
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http

fasthttp Fast HTTP implementation for Go. Currently fasthttp is successfully used by VertaMedia in a production serving up to 200K rps from more than

Jan 5, 2023
Simple GUI to convert Charles headers to golang's default http client (net/http)

Charles-to-Go Simple GUI to convert Charles headers to golang's default http client (net/http) Usage Compile code to a binary, go build -ldflags -H=wi

Dec 14, 2021
Lux - A web library collection based on net/http

Lux - A web library collection based on net/http

Jan 7, 2023
Fork of Go stdlib's net/http that works with alternative TLS libraries like refraction-networking/utls.

github.com/ooni/oohttp This repository contains a fork of Go's standard library net/http package including patches to allow using this HTTP code with

Sep 29, 2022
Drop-in replacement for Go net/http when running in AWS Lambda & API Gateway
Drop-in replacement for Go net/http when running in AWS Lambda & API Gateway

Package gateway provides a drop-in replacement for net/http's ListenAndServe for use in AWS Lambda & API Gateway, simply swap it out for gateway.Liste

Nov 24, 2022
A Discord ratelimiter for net/http

A Discord ratelimiter intended to be used with net/http clients using time/x/rate.

Nov 6, 2021
go stomp server base on net/http

stompserver go stomp server base on "net/http" base on "net/http" and "golang.org/x/net/websocket" so use one port, you can be WebServer or StompServe

Sep 22, 2022
IPIP.net officially supported IP database ipdb format parsing library

IPIP.net officially supported IP database ipdb format parsing library

Dec 27, 2022
EasyNet - A light net library with epoll

easyNet - NON BLOCKING IO Examples echo-server package main import ( "fmt" "g

Aug 24, 2022
A pluggable backend API that enforces the Event Sourcing Pattern for persisting & broadcasting application state changes
A pluggable backend API that enforces the Event Sourcing Pattern for persisting & broadcasting application state changes

A pluggable "Application State Gateway" that enforces the Event Sourcing Pattern for securely persisting & broadcasting application state changes

Nov 1, 2022
gRelay is an open source project written in Go that provides the circuit break pattern with a relay idea behind.
gRelay is an open source project written in Go that provides the circuit break pattern with a relay idea behind.

gRELAY gRelay is an open source project written in Go that provides: Circuit Break ✔️ Circuit Break + Relay ✔️ Concurrecny Safe ✔️ Getting start Insta

Sep 30, 2022
Go Domain Drived Design / Service repository pattern

Go Domain Drived Design / Service repository pattern Simple api domain drived design / service repository pattern API Overview every api (for each dom

Nov 28, 2022
screen sharing for developers https://screego.net/
screen sharing for developers https://screego.net/

screego/server screen sharing for developers Huge thanks to sipgate for sponsoring this project! Intro In the past I've had some problems sharing my s

Jan 1, 2023
ipx provides general purpose extensions to golang's IP functions in net package

ipx ipx is a library which provides a set of extensions on go's standart IP functions in net package. compability with net package ipx is fully compat

May 24, 2021
ConnPool is a thread safe connection pool for net.Conn interface.

ConnPool is a thread safe connection pool for net.Conn interface. It can be used to manage and reuse connections.

Dec 22, 2022
EasyTCP is a light-weight and less painful TCP server framework written in Go (Golang) based on the standard net package.

EasyTCP is a light-weight TCP framework written in Go (Golang), built with message router. EasyTCP helps you build a TCP server easily fast and less painful.

Jan 7, 2023
Cat Balancer is line based load balancer for net cat nc.
Cat Balancer is line based load balancer for net cat nc.

Cat Balancer Cat Balancer is line based load balancer for net cat nc. Usage cb [-p <producers-port>] [-c <consumers-port>] One Producer to One Consum

Jul 6, 2022