Skip to content

Commit

Permalink
Align features with julienschmidt/httprouter (#18)
Browse files Browse the repository at this point in the history
* Align features with julienschmidt/httprouter

* Add extra functionalities

* Tests refactor

* Add go.1.13 support
  • Loading branch information
Sergio Andrés Virviescas Santana authored Jan 21, 2020
1 parent 8c72a81 commit f905dab
Show file tree
Hide file tree
Showing 12 changed files with 1,208 additions and 1,442 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go:
- 1.10.x
- 1.11.x
- 1.12.x
- 1.13.x
- tip

os:
Expand Down
6 changes: 3 additions & 3 deletions examples/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"log"
"strings"

"github.com/elithrar/simple-scrypt"
scrypt "github.com/elithrar/simple-scrypt"
"github.com/fasthttp/router"
"github.com/valyala/fasthttp"
)
Expand Down Expand Up @@ -43,7 +43,7 @@ func parseBasicAuth(auth string) (username, password string, ok bool) {

// BasicAuth is the basic auth handler
func BasicAuth(h fasthttp.RequestHandler, requiredUser string, requiredPasswordHash []byte) fasthttp.RequestHandler {
return fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) {
return func(ctx *fasthttp.RequestCtx) {
// Get the Basic Authentication credentials
user, password, hasAuth := basicAuth(ctx)

Expand Down Expand Up @@ -77,7 +77,7 @@ func BasicAuth(h fasthttp.RequestHandler, requiredUser string, requiredPasswordH
// Request Basic Authentication otherwise
ctx.Error(fasthttp.StatusMessage(fasthttp.StatusUnauthorized), fasthttp.StatusUnauthorized)
ctx.Response.Header.Set("WWW-Authenticate", "Basic realm=Restricted")
})
}
}

// Index is the index handler
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/fasthttp/router
go 1.13

require (
github.com/savsgio/gotils v0.0.0-20190925070755-524bc4f47500
github.com/savsgio/gotils v0.0.0-20200117113501-90175b0fbe3f
github.com/valyala/bytebufferpool v1.0.0
github.com/valyala/fasthttp v1.8.0
)
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ github.com/klauspost/compress v1.8.2 h1:Bx0qjetmNjdFXASH02NSAREKpiaDwkO1DRZ3dV2K
github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/cpuid v1.2.1 h1:vJi+O/nMdFt0vqm8NZBI6wzALWdA2X+egi0ogNyrC/w=
github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/savsgio/gotils v0.0.0-20190925070755-524bc4f47500 h1:9Pi10H7E8E79/x2HSe1FmMGd7BJ1WAqDKzwjpv+ojFg=
github.com/savsgio/gotils v0.0.0-20190925070755-524bc4f47500/go.mod h1:lHhJedqxCoHN+zMtwGNTXWmF0u9Jt363FYRhV6g0CdY=
github.com/savsgio/gotils v0.0.0-20200117113501-90175b0fbe3f h1:PgA+Olipyj258EIEYnpFFONrrCcAIWNUNoFhUfMqAGY=
github.com/savsgio/gotils v0.0.0-20200117113501-90175b0fbe3f/go.mod h1:lHhJedqxCoHN+zMtwGNTXWmF0u9Jt363FYRhV6g0CdY=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.8.0 h1:actnGGBYtGQmxVaZxyZpp57Vcc2NhcO7mMN0IMwCC0w=
Expand Down
189 changes: 100 additions & 89 deletions path.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,50 +7,14 @@ package router

import (
"strings"
"sync"

"github.com/savsgio/gotils"
)

type cleanPathBuffer struct {
n int
r int
w int
trailing bool
buf []byte
}

var cleanPathBufferPool = sync.Pool{
New: func() interface{} {
return &cleanPathBuffer{
n: 0,
r: 0,
w: 1,
trailing: false,
buf: make([]byte, 140),
}
},
}

func (cpb *cleanPathBuffer) reset() {
cpb.n = 0
cpb.r = 0
cpb.w = 1
cpb.trailing = false
// cpb.buf = cpb.buf[:0]
}

func acquireCleanPathBuffer() *cleanPathBuffer {
return cleanPathBufferPool.Get().(*cleanPathBuffer)
}

func releaseCleanPathBuffer(cpb *cleanPathBuffer) {
cpb.reset()
cleanPathBufferPool.Put(cpb)
}
const stackBufSize = 128

// CleanPath is the URL version of path.Clean, it returns a canonical URL path
// for path, eliminating . and .. elements.
// for p, eliminating . and .. elements.
//
// The following rules are applied iteratively until no further processing can
// be done:
Expand All @@ -62,86 +26,133 @@ func releaseCleanPathBuffer(cpb *cleanPathBuffer) {
// that is, replace "/.." by "/" at the beginning of a path.
//
// If the result of this process is an empty string, "/" is returned
func CleanPath(path string) string {
cpb := acquireCleanPathBuffer()
cleanPathWithBuffer(cpb, path)
func CleanPath(p string) string {
// Turn empty string into "/"
if p == "" {
return "/"
}

s := string(cpb.buf)
releaseCleanPathBuffer(cpb)
// Reasonably sized buffer on stack to avoid allocations in the common case.
// If a larger buffer is required, it gets allocated dynamically.
buf := make([]byte, 0, stackBufSize)

return s
}
n := len(p)

func cleanPathWithBuffer(cpb *cleanPathBuffer, path string) {
// Turn empty string into "/"
if path == "" {
cpb.buf = append(cpb.buf[:0], '/')
return
}
// Invariants:
// reading from path; r is index of next byte to process.
// writing to buf; w is index of next byte to write.

cpb.n = len(path)
cpb.buf = gotils.ExtendByteSlice(cpb.buf, len(path)+1)
cpb.buf[0] = '/'
// path must start with '/'
r := 1
w := 1

cpb.trailing = cpb.n > 2 && path[cpb.n-1] == '/'
if p[0] != '/' {
r = 0

if n+1 > stackBufSize {
buf = make([]byte, n+1)
} else {
buf = buf[:n+1]
}
buf[0] = '/'
}

trailing := n > 1 && p[n-1] == '/'

// A bit more clunky without a 'lazybuf' like the path package, but the loop
// gets completely inlined (bufApp). So in contrast to the path package this
// loop has no expensive function calls (except 1x make)
// gets completely inlined (bufApp calls).
// So in contrast to the path package this loop has no expensive function
// calls (except make, if needed).

for cpb.r < cpb.n {
// println(path[:cpb.r], " ####### ", string(path[cpb.r]), " ####### ", string(cpb.buf))
for r < n {
switch {
case path[cpb.r] == '/':
case p[r] == '/':
// empty path element, trailing slash is added after the end
cpb.r++
r++

case path[cpb.r] == '.' && cpb.r+1 == cpb.n:
cpb.trailing = true
cpb.r++
case p[r] == '.' && r+1 == n:
trailing = true
r++

case path[cpb.r] == '.' && path[cpb.r+1] == '/':
case p[r] == '.' && p[r+1] == '/':
// . element
cpb.r++
r += 2

case path[cpb.r] == '.' && path[cpb.r+1] == '.' && (cpb.r+2 == cpb.n || path[cpb.r+2] == '/'):
case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):
// .. element: remove to last /
cpb.r += 2
r += 3

if cpb.w > 1 {
if w > 1 {
// can backtrack
cpb.w--

for cpb.w > 1 && cpb.buf[cpb.w] != '/' {
cpb.w--
w--

if len(buf) == 0 {
for w > 1 && p[w] != '/' {
w--
}
} else {
for w > 1 && buf[w] != '/' {
w--
}
}

}

default:
// real path element.
// add slash if needed
if cpb.w > 1 {
cpb.buf[cpb.w] = '/'
cpb.w++
// Real path element.
// Add slash if needed
if w > 1 {
bufApp(&buf, p, w, '/')
w++
}

// copy element
for cpb.r < cpb.n && path[cpb.r] != '/' {
cpb.buf[cpb.w] = path[cpb.r]
cpb.w++
cpb.r++
// Copy element
for r < n && p[r] != '/' {
bufApp(&buf, p, w, p[r])
w++
r++
}
}
}

// re-append trailing slash
if cpb.trailing && cpb.w > 1 {
cpb.buf[cpb.w] = '/'
cpb.w++
// Re-append trailing slash
if trailing && w > 1 {
bufApp(&buf, p, w, '/')
w++
}

// If the original string was not modified (or only shortened at the end),
// return the respective substring of the original string.
// Otherwise return a new string from the buffer.
if len(buf) == 0 {
return p[:w]
}
return string(buf[:w])
}

// Internal helper to lazily create a buffer if necessary.
// Calls to this function get inlined.
func bufApp(buf *[]byte, s string, w int, c byte) {
b := *buf
if len(b) == 0 {
// No modification of the original string so far.
// If the next character is the same as in the original string, we do
// not yet have to allocate a buffer.
if s[w] == c {
return
}

cpb.buf = cpb.buf[:cpb.w]
// Otherwise use either the stack buffer, if it is large enough, or
// allocate a new buffer on the heap, and copy all previous characters.
if l := len(s); l > cap(b) {
*buf = make([]byte, len(s))
} else {
*buf = (*buf)[:l]
}
b = *buf

copy(b, s[:w])
}
b[w] = c
}

// returns all possible paths when the original path has optional arguments
Expand Down
Loading

0 comments on commit f905dab

Please sign in to comment.