Ejemplo n.º 1
0
// A constructor for middleware
// that writes its own "tag" into the RW and does nothing else.
// Useful in checking if a chain is behaving in the right order.
func tagMiddleware(tag string) Constructor {
	return func(h wctx.Handler) wctx.Handler {
		return wctx.HandleFunc(func(c context.Context, w http.ResponseWriter, r *http.Request) {
			w.Write([]byte(tag))
			h.ServeHTTP(c, w, r)
		})
	}
}
Ejemplo n.º 2
0
Archivo: extra.go Proyecto: orian/chain
// StripPrefix returns a handler that serves HTTP requests
// by removing the given prefix from the request URL's Path
// and invoking the handler h. StripPrefix handles a
// request for a path that doesn't begin with prefix by
// replying with an HTTP 404 not found error.
func StripPrefix(prefix string) func(wctx.Handler) wctx.Handler {
	return func(h wctx.Handler) wctx.Handler {
		if prefix == "" {
			return h
		}
		return wctx.HandleFunc(func(c context.Context, w http.ResponseWriter, r *http.Request) {
			if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) {
				r.URL.Path = p
				h.ServeHTTP(c, w, r)
			}
			// else {
			// 	// problematic case
			// 	NotFound(w, r)
			// }
		})
	}
}
Ejemplo n.º 3
0
			w.Write([]byte(tag))
			h.ServeHTTP(c, w, r)
		})
	}
}

// Not recommended (https://golang.org/pkg/reflect/#Value.Pointer),
// but the best we can do.
func funcsEqual(f1, f2 interface{}) bool {
	val1 := reflect.ValueOf(f1)
	val2 := reflect.ValueOf(f2)
	return val1.Pointer() == val2.Pointer()
}

var testApp = wctx.HandleFunc(func(c context.Context, w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("app\n"))
})

// Tests creating a new chain
func TestNew(t *testing.T) {
	c1 := func(h wctx.Handler) wctx.Handler {
		return nil
	}
	// c2 := func(h wctx.Handler) wctx.Handler {
	// 	return wctx.StripPrefix("potato", nil)
	// }

	slice := []Constructor{c1, extra.StripPrefix("potato")}

	chain := New(slice...)
	assert.True(t, funcsEqual(chain.constructors[0], slice[0]))
Ejemplo n.º 4
0
Archivo: chain.go Proyecto: orian/chain
// ThenFunc works identically to Then, but takes
// a HandlerFunc instead of a Handler.
//
// The following two statements are equivalent:
//     c.Then(wctx.HandleFunc(fn))
//     c.ThenFunc(fn)
//
// ThenFunc provides all the guarantees of Then.
func (c Chain) ThenFunc(fn wctx.HandleFunc) wctx.Handler {
	if fn == nil {
		return c.Then(nil)
	}
	return c.Then(wctx.HandleFunc(fn))
}