prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
/v5"
"golang.org/x/time/rate"
)
// RateLimiterStore is the interface to be implemented by custom stores.
type RateLimiterStore interface {
Allow(identifier string) (bool, error)
}
// RateLimiterConfig defines the configuration for the rate limiter
type RateLimiterConfig struct {
Skipper Skipper
BeforeFunc Befo... | andler func(c *echo.Context, identifier string, err error) error
}
// Extractor is used to extract data from *echo.Context
type Extractor func(c *echo.Context) (string, error)
// ErrRateLimitExceeded denotes an error raised when rate limit is exceeded
va | // ErrorHandler provides a handler to be called when IdentifierExtractor returns an error
ErrorHandler func(c *echo.Context, err error) error
// DenyHandler provides a handler to be called when RateLimiter denies access
DenyH | {
"filepath": "middleware/rate_limiter.go",
"language": "go",
"file_size": 8709,
"cut_index": 716,
"middle_length": 229
} |
to prevent timing attacks
if subtle.ConstantTimeCompare([]byte(key), []byte("valid-key")) == 1 {
return true, nil
}
// Special case for testing error handling
if key == "error-key" { // Error path doesn't need constant-time
return false, errors.New("some user defined error")
}
return false, nil
}
func Tes... | ewareChain(c)
assert.NoError(t, err)
assert.True(t, handlerCalled)
}
func TestKeyAuthWithConfig(t *testing.T) {
var testCases = []struct {
name string
givenRequestFunc func() *http.Request
givenRequest func(req *http.Req | yValidator)(handler)
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(echo.HeaderAuthorization, "Bearer valid-key")
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := middl | {
"filepath": "middleware/key_auth_test.go",
"language": "go",
"file_size": 10694,
"cut_index": 921,
"middle_length": 229
} |
htText: © 2015 LabStack LLC and Echo contributors
package middleware
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/assert"
)
func TestMethodOverride(t *testing.T) {
e := echo.New()
m := MethodOverride()
h := func(c *echo.Context) error ... | h := func(c *echo.Context) error {
return c.String(http.StatusOK, "test")
}
// Override with form parameter
m, err := MethodOverrideConfig{Getter: MethodFromForm("_method")}.ToMiddleware()
assert.NoError(t, err)
req := httptest.NewRequest(http.Meth | TTPMethodOverride, http.MethodDelete)
c := e.NewContext(req, rec)
err := m(h)(c)
assert.NoError(t, err)
assert.Equal(t, http.MethodDelete, req.Method)
}
func TestMethodOverride_formParam(t *testing.T) {
e := echo.New()
| {
"filepath": "middleware/method_override_test.go",
"language": "go",
"file_size": 2317,
"cut_index": 563,
"middle_length": 229
} |
e(t2.URL)
targets := []*ProxyTarget{
{
Name: "target 1",
URL: url1,
},
{
Name: "target 2",
URL: url2,
},
}
rb := NewRandomBalancer(nil)
// must add targets:
for _, target := range targets {
assert.True(t, rb.AddTarget(target))
}
// must ignore duplicates:
for _, target := range targets... | targets {
assert.True(t, rb.RemoveTarget(target.Name))
}
assert.False(t, rb.RemoveTarget("unknown target"))
// Round-robin
rrb := NewRoundRobinBalancer(targets)
e = echo.New()
e.Use(ProxyWithConfig(ProxyConfig{Balancer: rrb}))
rec = httptest.N | test.NewRecorder()
e.ServeHTTP(rec, req)
body := rec.Body.String()
expected := map[string]bool{
"target 1": true,
"target 2": true,
}
assert.Condition(t, func() bool {
return expected[body]
})
for _, target := range | {
"filepath": "middleware/proxy_test.go",
"language": "go",
"file_size": 30524,
"cut_index": 1331,
"middle_length": 229
} |
package middleware
import (
"bufio"
"errors"
"github.com/stretchr/testify/assert"
"net"
"net/http"
"net/http/httptest"
"regexp"
"testing"
)
func TestRewriteURL(t *testing.T) {
var testCases = []struct {
whenURL string
expectPath string
expectRawPath string
expectQuery string
expectErr ... | +",
expectRawPath: "",
expectQuery: "test=1",
},
{
whenURL: "http://localhost:8080/users/%20a/orders/%20aa",
expectPath: "/user/ a/order/ aa",
expectRawPath: "",
},
{
whenURL: "http://localhost:8080/%47%6f%2f?test | whenURL: "/ol%64", // `%64` is decoded `d`
expectPath: "/old",
expectRawPath: "/ol%64",
},
{
whenURL: "http://localhost:8080/users/+_+/orders/___++++?test=1",
expectPath: "/user/+_+/order/___+++ | {
"filepath": "middleware/middleware_test.go",
"language": "go",
"file_size": 3740,
"cut_index": 614,
"middle_length": 229
} |
package middleware
import (
"bytes"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/assert"
)
func TestRecover(t *testing.T) {
e := echo.New()
buf := new(bytes.Buffer)
e.Logger = slog.New(&discardHandler{})
req := httptest.NewRequest... | .Equal(t, http.StatusOK, rec.Code) // status is still untouched. err is returned from middleware chain
assert.Contains(t, buf.String(), "") // nothing is logged
}
func TestRecover_skipper(t *testing.T) {
e := echo.New()
req := httptest.NewRequest( | ror(), "[PANIC RECOVER] test goroutine")
var pse *PanicStackError
if errors.As(err, &pse) {
assert.Contains(t, string(pse.Stack), "middleware/recover.go")
} else {
assert.Fail(t, "not of type PanicStackError")
}
assert | {
"filepath": "middleware/recover_test.go",
"language": "go",
"file_size": 3606,
"cut_index": 614,
"middle_length": 229
} |
5"
"github.com/stretchr/testify/assert"
)
type middlewareGenerator func() echo.MiddlewareFunc
func TestRedirectHTTPSRedirect(t *testing.T) {
var testCases = []struct {
whenHost string
whenHeader http.Header
expectLocation string
expectStatusCode int
}{
{
whenHost: "labstack.com... | tc.whenHeader)
assert.Equal(t, tc.expectStatusCode, res.Code)
assert.Equal(t, tc.expectLocation, res.Header().Get(echo.HeaderLocation))
})
}
}
func TestRedirectHTTPSWWWRedirect(t *testing.T) {
var testCases = []struct {
whenHost strin | eaderXForwardedProto: {"https"}},
expectLocation: "",
expectStatusCode: http.StatusOK,
},
}
for _, tc := range testCases {
t.Run(tc.whenHost, func(t *testing.T) {
res := redirectTest(HTTPSRedirect, tc.whenHost, | {
"filepath": "middleware/redirect_test.go",
"language": "go",
"file_size": 7865,
"cut_index": 716,
"middle_length": 229
} |
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/assert"
)
func TestRequestID(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
handler... | estIDWithConfig(RequestIDConfig{
Skipper: func(c *echo.Context) bool {
return true
},
Generator: func() string {
generatorCalled = true
return "customGenerator"
},
}))
req := httptest.NewRequest(http.MethodGet, "/", nil)
res := httptes | HeaderXRequestID), 32)
}
func TestMustRequestIDWithConfig_skipper(t *testing.T) {
e := echo.New()
e.GET("/", func(c *echo.Context) error {
return c.String(http.StatusTeapot, "test")
})
generatorCalled := false
e.Use(Requ | {
"filepath": "middleware/request_id_test.go",
"language": "go",
"file_size": 4571,
"cut_index": 614,
"middle_length": 229
} |
Header.Set(echo.HeaderContentLength, strconv.Itoa(int(reader.Size())))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
req.Header.Set(echo.HeaderXRealIP, "8.8.8.8")
req.Header.Set("User-Agent", "curl/7.68.0")
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
logAttrs := map[string]any{}
asse... |
"time": "x",
"latency": 123,
}
assert.Equal(t, expect, logAttrs)
}
func TestRequestLoggerError(t *testing.T) {
old := slog.Default()
t.Cleanup(func() {
slog.SetDefault(old)
})
e := echo.New()
buf := new(bytes.Buffer)
e.Logger = slog.Ne | d": "POST",
"uri": "/test",
"status": float64(418),
"bytes_in": "13",
"host": "example.com",
"bytes_out": float64(2),
"user_agent": "curl/7.68.0",
"remote_ip": "8.8.8.8",
"request_id": "", | {
"filepath": "middleware/request_logger_test.go",
"language": "go",
"file_size": 17585,
"cut_index": 1331,
"middle_length": 229
} |
message=rate limit exceeded"},
{id: "127.0.0.1", expectErr: "code=429, message=rate limit exceeded"},
{id: "127.0.0.1", expectErr: "code=429, message=rate limit exceeded"},
{id: "127.0.0.1", expectErr: "code=429, message=rate limit exceeded"},
}
for _, tc := range testCases {
req := httptest.NewRequest(http... | toreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3})
assert.Panics(t, func() {
RateLimiterWithConfig(RateLimiterConfig{})
})
assert.NotPanics(t, func() {
RateLimiterWithConfig(RateLimiterConfig{Store: inMemoryStore})
})
}
func TestRat | ualError(t, err, tc.expectErr)
} else {
assert.NoError(t, err)
}
assert.Equal(t, http.StatusOK, rec.Code)
}
}
func TestMustRateLimiterWithConfig_panicBehaviour(t *testing.T) {
var inMemoryStore = NewRateLimiterMemoryS | {
"filepath": "middleware/rate_limiter_test.go",
"language": "go",
"file_size": 17806,
"cut_index": 1331,
"middle_length": 229
} |
htText: © 2015 LabStack LLC and Echo contributors
package middleware
import (
"github.com/labstack/echo/v5"
)
// RequestIDConfig defines the config for RequestID middleware.
type RequestIDConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Generator defines a function to generat... | etHeader (`X-Request-ID`) header value or when
// the header value is empty, generates that value and sets request ID to response
// as RequestIDConfig.TargetHeader (`X-Request-Id`) value.
func RequestID() echo.MiddlewareFunc {
return RequestIDWithConfig( | text, requestID string)
// TargetHeader defines what header to look for to populate the id.
// Optional. Default value is `X-Request-Id`
TargetHeader string
}
// RequestID returns a middleware that reads RequestIDConfig.Targ | {
"filepath": "middleware/request_id.go",
"language": "go",
"file_size": 2372,
"cut_index": 563,
"middle_length": 229
} |
htText: © 2015 LabStack LLC and Echo contributors
package middleware
import (
"errors"
"maps"
"regexp"
"github.com/labstack/echo/v5"
)
// RewriteConfig defines the config for Rewrite middleware.
type RewriteConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Rules defines th... | apture group in the values can be retrieved by index e.g. $1, $2 and so on.
// Example:
// "^/old/[0.9]+/": "/new",
// "^/api/.+?/(.*)": "/v2/$1",
RegexRules map[*regexp.Regexp]string
}
// Rewrite returns a Rewrite middleware.
//
// Rewrite mi | "/js/*": "/public/javascripts/$1",
// "/users/*/orders/*": "/user/$1/order/$2",
// Required.
Rules map[string]string
// RegexRules defines the URL path rewrite rules using regexp.Rexexp with captures
// Every c | {
"filepath": "middleware/rewrite.go",
"language": "go",
"file_size": 2328,
"cut_index": 563,
"middle_length": 229
} |
directConfig defines the config for Redirect middleware.
type RedirectConfig struct {
// Skipper defines a function to skip middleware.
Skipper
// Status code to be used when redirecting the request.
// Optional. Default value http.StatusMovedPermanently.
Code int
redirect redirectLogic
}
// redirectLogic repr... | g is the HTTPS WWW Redirect middleware config.
var RedirectHTTPSWWWConfig = RedirectConfig{redirect: redirectHTTPSWWW}
// RedirectNonHTTPSWWWConfig is the non HTTPS WWW Redirect middleware config.
var RedirectNonHTTPSWWWConfig = RedirectConfig{redirect: r | func(scheme, host, uri string) (ok bool, url string)
const www = "www."
// RedirectHTTPSConfig is the HTTPS Redirect middleware config.
var RedirectHTTPSConfig = RedirectConfig{redirect: redirectHTTPS}
// RedirectHTTPSWWWConfi | {
"filepath": "middleware/redirect.go",
"language": "go",
"file_size": 6132,
"cut_index": 716,
"middle_length": 229
} |
fig for Secure middleware.
type SecureConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// XSSProtection provides protection against cross-site scripting attack (XSS)
// by setting the `X-XSS-Protection` header.
// Optional. Default value "1; mode=block".
XSSProtection string
//... | content is not embedded into other sites.provides protection against
// clickjacking.
// Optional. Default value "SAMEORIGIN".
// Possible values:
// - "SAMEORIGIN" - The page can only be displayed in a frame on the same origin as the page itself.
// | ring
// XFrameOptions can be used to indicate whether or not a browser should
// be allowed to render a page in a <frame>, <iframe> or <object> .
// Sites can use this to avoid clickjacking attacks, by ensuring that their
// | {
"filepath": "middleware/secure.go",
"language": "go",
"file_size": 5620,
"cut_index": 716,
"middle_length": 229
} |
package middleware
import (
"errors"
"net/http"
"strings"
"github.com/labstack/echo/v5"
)
// AddTrailingSlashConfig is the middleware config for adding trailing slash to the request.
type AddTrailingSlashConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Status code to be us... | ilingSlashConfig{})
}
// AddTrailingSlashWithConfig returns an AddTrailingSlash middleware with config or panics on invalid configuration.
func AddTrailingSlashWithConfig(config AddTrailingSlashConfig) echo.MiddlewareFunc {
return toMiddlewareOrPanic(con | a root level (before router) middleware which adds a
// trailing slash to the request `URL#Path`.
//
// Usage `Echo#Pre(AddTrailingSlash())`
func AddTrailingSlash() echo.MiddlewareFunc {
return AddTrailingSlashWithConfig(AddTra | {
"filepath": "middleware/slash.go",
"language": "go",
"file_size": 4783,
"cut_index": 614,
"middle_length": 229
} |
LogStatus: true,
// LogURI: true,
// HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code
// LogValuesFunc: func(c *echo.Context, v middleware.RequestLoggerValues) error {
// if v.Error == nil {
// logger.LogAttrs(context.Background(), slog.LevelInfo,... | ddleware.RequestLoggerConfig{
// LogStatus: true,
// LogURI: true,
// HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code
// LogValuesFunc: func(c *echo.Context, v middleware.RequestLoggerVa | og.String("uri", v.URI),
// slog.Int("status", v.Status),
// slog.String("err", v.Error.Error()),
// )
// }
// return nil
// },
// }))
//
// Example for `fmt.Printf`
// e.Use(middleware.RequestLoggerWithConfig(mi | {
"filepath": "middleware/request_logger.go",
"language": "go",
"file_size": 16143,
"cut_index": 921,
"middle_length": 229
} |
5"
"github.com/stretchr/testify/assert"
)
func TestAddTrailingSlashWithConfig(t *testing.T) {
var testCases = []struct {
whenURL string
whenMethod string
expectPath string
expectLocation []string
expectStatus int
}{
{
whenURL: "/add-slash",
whenMethod: http.MethodGet,
... | or open redirect vulnerability
{
whenURL: "http://localhost:1323/%5Cexample.com",
expectPath: `/\example.com`,
expectLocation: []string{`/example.com/`},
},
{
whenURL: `http://localhost:1323/\example.com`,
expectPath: | h",
expectLocation: []string{`/add-slash/?key=value`},
},
{
whenURL: "/",
whenMethod: http.MethodConnect,
expectPath: "/",
expectLocation: nil,
expectStatus: http.StatusOK,
},
// cases f | {
"filepath": "middleware/slash_test.go",
"language": "go",
"file_size": 6899,
"cut_index": 716,
"middle_length": 229
} |
root
e.Use(StaticWithConfig(StaticConfig{
Root: "testdata/dist/public",
}))
// all requests to `/api/*` will end up in echo handlers (assuming there is not `api` folder and files)
api := e.Group("/api")
users := api.Group("/users")
users.GET("/info", func(c *echo.Context) error {
return c.String(http.Status... | ody.String(), "<h1>Hello from index</h1>\n")
}
func TestStatic(t *testing.T) {
var testCases = []struct {
name string
givenConfig *StaticConfig
givenAttachedToGroup string
whenURL string
expectContains | rt.Equal(t, "users info", rec.Body.String())
req = httptest.NewRequest(http.MethodGet, "/index.html", nil)
rec = httptest.NewRecorder()
e.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Contains(t, rec.B | {
"filepath": "middleware/static_test.go",
"language": "go",
"file_size": 14843,
"cut_index": 921,
"middle_length": 229
} |
"github.com/stretchr/testify/require"
)
type discardHandler struct {
slog.JSONHandler
}
func (d *discardHandler) Enabled(context.Context, slog.Level) bool { return false }
func Test_matchScheme(t *testing.T) {
tests := []struct {
domain, pattern string
expected bool
}{
{
domain: "http://example... | cted, matchScheme(v.domain, v.pattern))
}
}
func TestRandomString(t *testing.T) {
var testCases = []struct {
name string
whenLength uint8
expect string
}{
{
name: "ok, 16",
whenLength: 16,
},
{
name: "ok, 32", | xample.com",
pattern: "https://example.com",
expected: false,
},
{
domain: "https://example.com",
pattern: "http://example.com",
expected: false,
},
}
for _, v := range tests {
assert.Equal(t, v.expe | {
"filepath": "middleware/util_test.go",
"language": "go",
"file_size": 8705,
"cut_index": 716,
"middle_length": 229
} |
"
"github.com/stretchr/testify/assert"
)
func TestServeWithHandler(t *testing.T) {
handler := func(c *echo.Context) error {
return c.String(http.StatusOK, c.QueryParam("key"))
}
testConf := ContextConfig{
QueryValues: url.Values{"key": []string{"value"}},
}
resp := testConf.ServeWithHandler(t, handler)
as... | WithHandler(t, handler, customErrHandler)
assert.Equal(t, http.StatusBadRequest, resp.Code)
assert.Equal(t, `{"message":"something went wrong"}`+"\n", resp.Body.String())
}
func TestToContext_QueryValues(t *testing.T) {
testConf := ContextConfig{
Qu | .NewHTTPError(http.StatusBadRequest, "something went wrong")
}
testConf := ContextConfig{
QueryValues: url.Values{"key": []string{"value"}},
}
customErrHandler := echo.DefaultHTTPErrorHandler(true)
resp := testConf.Serve | {
"filepath": "echotest/context_test.go",
"language": "go",
"file_size": 3745,
"cut_index": 614,
"middle_length": 229
} |
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/assert"
)
func TestSecure(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
h := func(... | sportSecurity))
assert.Equal(t, "", rec.Header().Get(echo.HeaderContentSecurityPolicy))
assert.Equal(t, "", rec.Header().Get(echo.HeaderReferrerPolicy))
}
func TestSecureWithConfig(t *testing.T) {
e := echo.New()
h := func(c *echo.Context) error {
r | XXSSProtection))
assert.Equal(t, "nosniff", rec.Header().Get(echo.HeaderXContentTypeOptions))
assert.Equal(t, "SAMEORIGIN", rec.Header().Get(echo.HeaderXFrameOptions))
assert.Equal(t, "", rec.Header().Get(echo.HeaderStrictTran | {
"filepath": "middleware/secure_test.go",
"language": "go",
"file_size": 4742,
"cut_index": 614,
"middle_length": 229
} |
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
package middleware
import (
"errors"
"io/fs"
"os"
)
// We ignore these errors as there could be handler that matches request path.
func isIgnorableOpenFileError(err error) bool {
if os.IsNotExist(err) {
return ... |
// errors in the middleware/handler chain. Otherwise we might end up with status 500 instead of finding a route
// or return 404 not found.
var pErr *fs.PathError
if errors.As(err, &pErr) {
err = pErr.Err
return err.Error() == "invalid argument"
| as invalid. Previously it would result you `fs.ErrNotExist`.
// Also `fs.Open` on all OSes does not accept ``, `.`, `..` at all.
//
// so we need to treat those errors the same as `fs.ErrNotExists` so we can continue handling | {
"filepath": "middleware/static_other.go",
"language": "go",
"file_size": 1016,
"cut_index": 512,
"middle_length": 229
} |
"
"strings"
"testing"
"github.com/labstack/echo/v5"
)
// ContextConfig is configuration for creating echo.Context for testing purposes.
type ContextConfig struct {
// Request will be used instead of default `httptest.NewRequest(http.MethodGet, "/", nil)`
Request *http.Request
// Response will be used instead o... | ues creates form-urlencoded form out of given values. If there is no
// `content-type` header it will be set to `application/x-www-form-urlencoded`
// In case Request was not set the Request.Method is set to `POST`
//
// FormValues, MultipartForm and J | eader value
Headers http.Header
// PathValues initializes context.PathValues with given value.
PathValues echo.PathValues
// RouteInfo initializes context.RouteInfo() with given value
RouteInfo *echo.RouteInfo
// FormVal | {
"filepath": "echotest/context.go",
"language": "go",
"file_size": 5483,
"cut_index": 716,
"middle_length": 229
} |
dleware.
Skipper Skipper
// Root directory from where the static content is served (relative to given Filesystem).
// `Root: "."` means root folder from Filesystem.
// Required.
Root string
// Filesystem provides access to the static content.
// Optional. Defaults to echo.Filesystem (serves files from `.` fold... | gnoring of the base of the URL path.
// Example: when assigning a static middleware to a non root path group,
// the filesystem path is not doubled
// Optional. Default value false.
IgnoreBase bool
// DisablePathUnescaping disables path parameter (pa | found requests to root so that
// SPA (single-page application) can handle the routing.
// Optional. Default value false.
HTML5 bool
// Enable directory browsing.
// Optional. Default value false.
Browse bool
// Enable i | {
"filepath": "middleware/static.go",
"language": "go",
"file_size": 9411,
"cut_index": 921,
"middle_length": 229
} |
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
package echotest
import (
"os"
"path/filepath"
"runtime"
"testing"
)
type loadBytesOpts func([]byte) []byte
// TrimNewlineEnd instructs LoadBytes to remove `\n` from the end of loaded file.
func TrimNewlineEnd(b... | s(t *testing.T, name string, callDepth int) []byte {
_, b, _, _ := runtime.Caller(callDepth)
basepath := filepath.Dir(b)
path := filepath.Join(basepath, name) // relative path
bytes, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return | (where test file is) package
// directory.
func LoadBytes(t *testing.T, name string, opts ...loadBytesOpts) []byte {
bytes := loadBytes(t, name, 2)
for _, f := range opts {
bytes = f(bytes)
}
return bytes
}
func loadByte | {
"filepath": "echotest/reader.go",
"language": "go",
"file_size": 1009,
"cut_index": 512,
"middle_length": 229
} |
htText: © 2015 LabStack LLC and Echo contributors
package middleware
import (
"bufio"
"crypto/rand"
"fmt"
"io"
"net/url"
"strings"
"sync"
)
const (
_ = int64(1 << (10 * iota)) // ignore first value by assigning to blank identifier
// KB is 1 KiloByte = 1024 bytes
KB
// MB is 1 Megabyte = 1_048_576 bytes
... | andomStringGenerator(length uint8) func() string {
return func() string {
return randomString(length)
}
}
// https://tip.golang.org/doc/go1.19#:~:text=Read%20no%20longer%20buffers%20random%20data%20obtained%20from%20the%20operating%20system%20between% | 606_847_000 bytes
EB
)
func matchScheme(domain, pattern string) bool {
didx := strings.Index(domain, ":")
pidx := strings.Index(pattern, ":")
return didx != -1 && pidx != -1 && domain[:didx] == pattern[:pidx]
}
func createR | {
"filepath": "middleware/util.go",
"language": "go",
"file_size": 2932,
"cut_index": 563,
"middle_length": 229
} |
/**
* Module dependencies.
*/
var escapeHtml = require('escape-html')
var express = require('../../lib/express');
var verbose = process.env.NODE_ENV !== 'test'
var app = module.exports = express();
app.map = function(a, route){
route = route || '';
for (var key in a) {
switch (typeof a[key]) {
// ... | },
delete: function(req, res){
res.send('delete users');
}
};
var pets = {
list: function(req, res){
res.send('user ' + escapeHtml(req.params.uid) + '\'s pets')
},
delete: function(req, res){
res.send('delete ' + escapeHtml(req.pa | ey, route);
app[key](route, a[key]);
break;
}
}
};
var users = {
list: function(req, res){
res.send('user list');
},
get: function(req, res){
res.send('user ' + escapeHtml(req.params.uid))
| {
"filepath": "examples/route-map/index.js",
"language": "javascript",
"file_size": 1419,
"cut_index": 524,
"middle_length": 229
} |
trict'
/**
* Module dependencies.
*/
var express = require('../..');
var path = require('node:path');
var app = express();
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var methodOverride = require('method-override');
var site = require('./site');
var post = require('./post');
var use... |
// User
app.get('/users', user.list);
app.all('/user/:id{/:op}', user.load);
app.get('/user/:id', user.view);
app.get('/user/:id/view', user.view);
app.get('/user/:id/edit', user.edit);
app.put('/user/:id/edit', user.update);
// Posts
app.get('/posts' | p.use(logger('dev'));
}
app.use(methodOverride('_method'));
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }))
app.use(express.static(path.join(__dirname, 'public')));
// General
app.get('/', site.index); | {
"filepath": "examples/route-separation/index.js",
"language": "javascript",
"file_size": 1136,
"cut_index": 518,
"middle_length": 229
} |
/**
* Module dependencies.
*/
var express = require('../..');
var logger = require('morgan');
var path = require('node:path');
var app = express();
// log requests
app.use(logger('dev'));
// express on its own has no notion
// of a "file". The express.static()
// middleware checks for a file matching
// the `req... | dleware,
// thus it serves the file correctly by ignoring "/static"
app.use('/static', express.static(path.join(__dirname, 'public')));
// if for some reason you want to serve files from
// several directories, you can use express.static()
// multiple tim | d to "prefix" you may use
// the mounting feature of Connect, for example
// "GET /static/js/app.js" instead of "GET /js/app.js".
// The mount-path "/static" is simply removed before
// passing control to the express.static() mid | {
"filepath": "examples/static-files/index.js",
"language": "javascript",
"file_size": 1363,
"cut_index": 524,
"middle_length": 229
} |
express = require('../../..');
var fs = require('node:fs');
var path = require('node:path');
module.exports = function(parent, options){
var dir = path.join(__dirname, '..', 'controllers');
var verbose = options.verbose;
fs.readdirSync(dir).forEach(function(name){
var file = path.join(dir, name)
if (!fs.... | ews'));
// generate routes based
// on the exported methods
for (var key in obj) {
// "reserved" exports
if (~['name', 'prefix', 'engine', 'before'].indexOf(key)) continue;
// route exports
switch (key) {
case ' | = express();
var handler;
var method;
var url;
// allow specifying the view engine
if (obj.engine) app.set('view engine', obj.engine);
app.set('views', path.join(__dirname, '..', 'controllers', name, 'vi | {
"filepath": "examples/mvc/lib/boot.js",
"language": "javascript",
"file_size": 2263,
"cut_index": 563,
"middle_length": 229
} |
trict'
/**
* Module dependencies.
*/
var express = require('../../');
var path = require('node:path');
var app = module.exports = express();
// path to where the files are stored on disk
var FILES_DIR = path.join(__dirname, 'files')
app.get('/', function(req, res){
res.send('<ul>' +
'<li>Download <a href="... | t) {
res.download(req.params.file.join('/'), { root: FILES_DIR }, function (err) {
if (!err) return; // file sent
if (err.status !== 404) return next(err); // non-404 error
// file for download not found
res.statusCode = 404;
res.send | /a>.</li>' +
'<li>Download <a href="/files/CCTV大赛上海分赛区.txt">CCTV大赛上海分赛区.txt</a>.</li>' +
'</ul>')
});
// /files/* is accessed via req.params[0]
// but here we name it :file
app.get('/files/*file', function (req, res, nex | {
"filepath": "examples/downloads/index.js",
"language": "javascript",
"file_size": 1193,
"cut_index": 518,
"middle_length": 229
} |
redis first:
// https://redis.io/
// then:
// $ npm install redis
// $ redis-server
/**
* Module dependencies.
*/
var express = require('../..');
var path = require('node:path');
var redis = require('redis');
var db = redis.createClient();
var app = express();
app.use(express.static(path.join(__dirname, 'public'... | , err);
process.exit(1);
}
}
/**
* GET search for :query.
*/
app.get('/search/{:query}', function (req, res, next) {
var query = req.params.query || '';
db.sMembers(query)
.then((vals) => res.send(vals))
.catch((err) => {
consol | Add('ferret', 'tobi');
await db.sAdd('ferret', 'loki');
await db.sAdd('ferret', 'jane');
await db.sAdd('cat', 'manny');
await db.sAdd('cat', 'luna');
} catch (err) {
console.error('Error initializing Redis:' | {
"filepath": "examples/search/index.js",
"language": "javascript",
"file_size": 1577,
"cut_index": 537,
"middle_length": 229
} |
trict'
/**
* Module dependencies.
*/
var express = require('../../');
var GithubView = require('./github-view');
var md = require('marked').parse;
var app = module.exports = express();
// register .md as an engine in express view system
app.engine('md', function(str, options, fn){
try {
var html = md(str);
... | res.locals, and locals passed
// work like they normally would
res.render('examples/markdown/views/index.md', { title: 'Example' });
});
app.get('/Readme.md', function(req, res){
// rendering a view from https://github.com/expressjs/express/blob/mas | ub repo to load files from it
app.set('views', 'expressjs/express');
// register a new view constructor
app.set('view', GithubView);
app.get('/', function(req, res){
// rendering a view relative to the repo.
// app.locals, | {
"filepath": "examples/view-constructor/index.js",
"language": "javascript",
"file_size": 1167,
"cut_index": 518,
"middle_length": 229
} |
ht(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var debug = require('debug')('express:view');
var path = require('node:path');
var fs = require('node:fs');
/**
* Module variables.
* @private
*/
var dirname = path.dirname;
var basename = pa... | ions
* @public
*/
function View(name, options) {
var opts = options || {};
this.defaultEngine = opts.defaultEngine;
this.ext = extname(name);
this.name = name;
this.root = opts.root;
if (!this.ext && !this.defaultEngine) {
throw new Er | he given `name`.
*
* Options:
*
* - `defaultEngine` the default template engine name
* - `engines` template engine require() cache
* - `root` root path for view lookup
*
* @param {string} name
* @param {object} opt | {
"filepath": "lib/view.js",
"language": "javascript",
"file_size": 3809,
"cut_index": 614,
"middle_length": 229
} |
= require('node:assert')
var express = require('../')
describe('app', function(){
describe('.locals', function () {
it('should default object with null prototype', function () {
var app = express()
assert.ok(app.locals)
assert.strictEqual(typeof app.locals, 'object')
assert.strictEqual(O... |
assert.ok(app.locals.settings)
assert.strictEqual(typeof app.locals.settings, 'object')
assert.strictEqual(app.locals.settings, app.settings)
assert.strictEqual(app.locals.settings.title, 'Express')
})
})
})
})
| e', 'Express') | {
"filepath": "test/app.locals.js",
"language": "javascript",
"file_size": 806,
"cut_index": 536,
"middle_length": 14
} |
var assert = require('node:assert')
var express = require('../')
, request = require('supertest');
describe('app', function(){
describe('.VERB()', function(){
it('should not get invoked without error handler on error', function(done) {
var app = express();
app.use(function(req, res, next){
... | ar d = false;
app.get('/', function(req, res, next){
next(new Error('fabricated error'));
}, function(req, res, next) {
a = true;
next();
}, function(err, req, res, next){
b = true;
assert.strictEq | boom!/, done);
});
it('should only call an error handling routing callback when an error is propagated', function(done){
var app = express();
var a = false;
var b = false;
var c = false;
v | {
"filepath": "test/app.routes.error.js",
"language": "javascript",
"file_size": 1504,
"cut_index": 524,
"middle_length": 229
} |
est = require('supertest');
describe('req', function(){
describe('.accepts(type)', function(){
it('should return true when Accept is not present', function(done){
var app = express();
app.use(function(req, res, next){
res.end(req.accepts('json') ? 'yes' : 'no');
});
request(app)... | app = express();
app.use(function(req, res, next){
res.end(req.accepts('json') ? 'yes' : 'no');
});
request(app)
.get('/')
.set('Accept', 'text/html')
.expect('no', done);
})
})
it('should accept an ar | nd(req.accepts('json') ? 'yes' : 'no');
});
request(app)
.get('/')
.set('Accept', 'application/json')
.expect('yes', done);
})
it('should return false otherwise', function(done){
var | {
"filepath": "test/req.accepts.js",
"language": "javascript",
"file_size": 2964,
"cut_index": 563,
"middle_length": 229
} |
est = require('supertest');
describe('req', function(){
describe('.protocol', function(){
it('should return the protocol string', function(done){
var app = express();
app.use(function(req, res){
res.end(req.protocol);
});
request(app)
.get('/')
.expect('http', done);... | ult to the socket addr if X-Forwarded-Proto not present', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res){
req.socket.encrypted = true;
res.end(req.protocol);
|
app.use(function(req, res){
res.end(req.protocol);
});
request(app)
.get('/')
.set('X-Forwarded-Proto', 'https')
.expect('https', done);
})
it('should defa | {
"filepath": "test/req.protocol.js",
"language": "javascript",
"file_size": 2579,
"cut_index": 563,
"middle_length": 229
} |
/**
* Module dependencies.
*/
var express = require('../../');
var logger = require('morgan');
var app = module.exports = express();
var test = app.get('env') === 'test'
if (!test) app.use(logger('dev'));
// error handling middleware have an arity of 4
// instead of the typical (req, res, next),
// otherwise the... | ');
});
app.get('/next', function(req, res, next){
// We can also pass exceptions to next()
// The reason for process.nextTick() is to show that
// next() can be called inside an async operation,
// in real life it can be a DB read or HTTP request |
// respond with 500 "Internal Server Error".
res.status(500);
res.send('Internal Server Error');
}
app.get('/', function () {
// Caught and passed down to the errorHandler middleware
throw new Error('something broke! | {
"filepath": "examples/error/index.js",
"language": "javascript",
"file_size": 1333,
"cut_index": 524,
"middle_length": 229
} |
'use strict'
// Fake user database
var users = [
{ name: 'TJ', email: 'tj@vision-media.ca' },
{ name: 'Tobi', email: 'tobi@vision-media.ca' }
];
exports.list = function(req, res){
res.render('users', { title: 'Users', users: users });
};
exports.load = function(req, res, next){
var id = req.params.id;
req... | });
};
exports.update = function(req, res){
// Normally you would handle all kinds of
// validation and save back to the db
var user = req.body.user;
req.user.name = user.name;
req.user.email = user.email;
res.redirect(req.get('Referrer') || | res.render('users/view', {
title: 'Viewing user ' + req.user.name,
user: req.user
});
};
exports.edit = function(req, res){
res.render('users/edit', {
title: 'Editing user ' + req.user.name,
user: req.user
| {
"filepath": "examples/route-separation/user.js",
"language": "javascript",
"file_size": 1006,
"cut_index": 512,
"middle_length": 229
} |
use strict'
/**
* Module dependencies.
*/
var express = require('../..');
var logger = require('morgan');
var vhost = require('vhost');
/*
edit /etc/hosts:
127.0.0.1 foo.example.com
127.0.0.1 bar.example.com
127.0.0.1 example.com
*/
// Main server app
var main = express();
if (!module.parent)... | ss();
app.use(vhost('*.example.com', redirect)); // Serves all subdomains via Redirect app
app.use(vhost('example.com', main)); // Serves top level domain via Main server app
/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console. | edirect app
var redirect = express();
redirect.use(function(req, res){
if (!module.parent) console.log(req.vhost);
res.redirect('http://example.com:3000/' + req.vhost[0]);
});
// Vhost app
var app = module.exports = expre | {
"filepath": "examples/vhost/index.js",
"language": "javascript",
"file_size": 1037,
"cut_index": 513,
"middle_length": 229
} |
express = require('../../');
var app = module.exports = express();
// Ad-hoc example resource method
app.resource = function(path, obj) {
this.get(path, obj.index);
this.get(path + '/:a..:b{.:format}', function(req, res){
var a = parseInt(req.params.a, 10);
var b = parseInt(req.params.b, 10);
var for... | er.
var User = {
index: function(req, res){
res.send(users);
},
show: function(req, res){
res.send(users[req.params.id] || { error: 'Cannot find user' });
},
destroy: function(req, res, id){
var destroyed = id in users;
delete us | 10);
obj.destroy(req, res, id);
});
};
// Fake records
var users = [
{ name: 'tj' }
, { name: 'ciaran' }
, { name: 'aaron' }
, { name: 'guillermo' }
, { name: 'simon' }
, { name: 'tobi' }
];
// Fake controll | {
"filepath": "examples/resource/index.js",
"language": "javascript",
"file_size": 2295,
"cut_index": 563,
"middle_length": 229
} |
express = require('../..');
var logger = require('morgan');
var path = require('node:path');
var session = require('express-session');
var methodOverride = require('method-override');
var app = module.exports = express();
// set our default template engine to "ejs"
// which prevents the need for using file extensions... | ssages.push(msg);
return this;
};
// log
if (!module.parent) app.use(logger('dev'));
// serve static files
app.use(express.static(path.join(__dirname, 'public')));
// session support
app.use(session({
resave: false, // don't save session if unmodifi | session
app.response.message = function(msg){
// reference `req.session` via the `this.req` reference
var sess = this.req.session;
// simply add the msg to an array for later
sess.messages = sess.messages || [];
sess.me | {
"filepath": "examples/mvc/index.js",
"language": "javascript",
"file_size": 2320,
"cut_index": 563,
"middle_length": 229
} |
'use strict'
var express = require('../../');
var app = module.exports = express();
var users = require('./db');
// so either you can deal with different types of formatting
// for expected response in index.js
app.get('/', function(req, res){
res.format({
html: function(){
res.send('<ul>' + users.map(fun... | tion format(path) {
var obj = require(path);
return function(req, res){
res.format(obj);
};
}
app.get('/users', format('./users'));
/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000 | + '\n';
}).join(''));
},
json: function(){
res.json(users);
}
});
});
// or you could write a tiny middleware like
// this to add a layer of abstraction
// and make things a bit more declarative:
func | {
"filepath": "examples/content-negotiation/index.js",
"language": "javascript",
"file_size": 1003,
"cut_index": 512,
"middle_length": 229
} |
var db = require('../../db');
exports.engine = 'hbs';
exports.before = function(req, res, next){
var id = req.params.user_id;
if (!id) return next();
// pretend to query a database...
process.nextTick(function(){
req.user = db.users[id];
// cant find that user
if (!req.user) return next('route');
... | show = function(req, res, next){
res.render('show', { user: req.user });
};
exports.update = function(req, res, next){
var body = req.body;
req.user.name = body.user.name;
res.message('Information updated!');
res.redirect('/user/' + req.user.id) | res.render('edit', { user: req.user });
};
exports. | {
"filepath": "examples/mvc/controllers/user/index.js",
"language": "javascript",
"file_size": 872,
"cut_index": 559,
"middle_length": 52
} |
/**
* Module dependencies.
*/
var createError = require('http-errors')
var express = require('../../');
var app = module.exports = express();
// Faux database
var users = [
{ name: 'tj' }
, { name: 'tobi' }
, { name: 'loki' }
, { name: 'jane' }
, { name: 'bandit' }
];
// Convert :to and :from to integ... | **
* GET index.
*/
app.get('/', function(req, res){
res.send('Visit /user/0 or /users/0-2');
});
/**
* GET :user.
*/
app.get('/user/:user', function (req, res) {
res.send('user ' + req.user.name);
});
/**
* GET users :from - :to.
*/
app.get( | ));
} else {
next();
}
});
// Load user by id
app.param('user', function(req, res, next, id){
req.user = users[id]
if (req.user) {
next();
} else {
next(createError(404, 'failed to find user'));
}
});
/ | {
"filepath": "examples/params/index.js",
"language": "javascript",
"file_size": 1353,
"cut_index": 524,
"middle_length": 229
} |
express = require('../../');
var path = require('node:path');
var app = module.exports = express();
var logger = require('morgan');
var silent = process.env.NODE_ENV === 'test'
// general config
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// our custom "verbose errors" setting
// w... | 404 since no other middleware
// will match /404 after this one, and we're not
// responding here
next();
});
app.get('/403', function(req, res, next){
// trigger a 403 error
var err = new Error('not allowed!');
err.status = 403;
next(err);
| ettings.env === 'production') app.disable('verbose errors')
silent || app.use(logger('dev'));
// Routes
app.get('/', function(req, res){
res.render('index.ejs');
});
app.get('/404', function(req, res, next){
// trigger a | {
"filepath": "examples/error-pages/index.js",
"language": "javascript",
"file_size": 2665,
"cut_index": 563,
"middle_length": 229
} |
/**
* Module dependencies.
*/
var express = require('../../');
var path = require('node:path');
var app = module.exports = express();
// Register ejs as .html. If we did
// not call this, we would need to
// name our views foo.ejs instead
// of foo.html. The __express method
// is simply a function that engines
... | thout this you would need to
// supply the extension to res.render()
// ex: res.render('users.html').
app.set('view engine', 'html');
// Placeholder users
var users = [
{ name: 'tobi', email: 'tobi@learnboost.com' },
{ name: 'loki', email: 'loki@learn | tml', require('ejs').__express);
// Optional since express defaults to CWD/views
app.set('views', path.join(__dirname, 'views'));
// Path to our public directory
app.use(express.static(path.join(__dirname, 'public')));
// Wi | {
"filepath": "examples/ejs/index.js",
"language": "javascript",
"file_size": 1331,
"cut_index": 524,
"middle_length": 229
} |
rts = express();
// create an error with .status. we
// can then use the property in our
// custom error handler (Connect respects this prop as well)
function error(status, msg) {
var err = new Error(msg);
err.status = status;
return err;
}
// if we wanted to supply more than JSON, we could
// use something si... | turn next(error(401, 'invalid api key'))
// all good, store req.key for route access
req.key = key;
next();
});
// map of valid api keys, typically mapped to
// account info with some sort of database like redis.
// api keys do _not_ serve as authe | o be invoked
app.use('/api', function(req, res, next){
var key = req.query['api-key'];
// key isn't present
if (!key) return next(error(400, 'api key required'));
// key is invalid
if (apiKeys.indexOf(key) === -1) re | {
"filepath": "examples/web-service/index.js",
"language": "javascript",
"file_size": 3044,
"cut_index": 614,
"middle_length": 229
} |
l redis first:
// https://redis.io/
// then:
// $ npm install redis
// $ redis-server
var express = require('../..');
var session = require('express-session');
var app = express();
// Populates req.session
app.use(session({
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't cr... | view this page in several browsers :)</p>';
}
res.send(body + '<p>viewed <strong>' + req.session.views + '</strong> times.</p>');
});
/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
} | ion.views = 1;
body += '<p>First time visiting? | {
"filepath": "examples/session/index.js",
"language": "javascript",
"file_size": 844,
"cut_index": 535,
"middle_length": 52
} |
df2-password')()
var path = require('node:path');
var session = require('express-session');
var app = module.exports = express();
// config
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// middleware
app.use(express.urlencoded())
app.use(session({
resave: false, // don't save se... | </p>';
if (msg) res.locals.message = '<p class="msg success">' + msg + '</p>';
next();
});
// placeholder database
var users = {
tj: { name: 'tj' }
};
// when you create a user, generate a salt
// and hash the password ('foobar' is the pass here)
| q, res, next){
var err = req.session.error;
var msg = req.session.success;
delete req.session.error;
delete req.session.success;
res.locals.message = '';
if (err) res.locals.message = '<p class="msg error">' + err + ' | {
"filepath": "examples/auth/index.js",
"language": "javascript",
"file_size": 3570,
"cut_index": 614,
"middle_length": 229
} |
../..');
var logger = require('morgan');
var session = require('express-session');
// pass the express to the connect redis module
// allowing it to inherit from session.Store
var RedisStore = require('connect-redis')(session);
var app = express();
app.use(logger('dev'));
// Populates req.session
app.use(session({
... | session.views) {
++req.session.views;
} else {
req.session.views = 1;
body += '<p>First time visiting? view this page in several browsers :)</p>';
}
res.send(body + '<p>viewed <strong>' + req.session.views + '</strong> times.</p>');
});
| '/', function(req, res){
var body = '';
if (req. | {
"filepath": "examples/session/redis.js",
"language": "javascript",
"file_size": 957,
"cut_index": 582,
"middle_length": 52
} |
express = require('../../lib/express');
var app = express();
// Example requests:
// curl http://localhost:3000/user/0
// curl http://localhost:3000/user/0/edit
// curl http://localhost:3000/user/1
// curl http://localhost:3000/user/1/edit (unauthorized since this is not you)
// curl -X DELETE htt... | user = users[req.params.id];
if (user) {
req.user = user;
next();
} else {
next(new Error('Failed to load user ' + req.params.id));
}
}
function andRestrictToSelf(req, res, next) {
// If our authenticated user is the user we are viewi | 'ciaran', email: 'ciaranj@gmail.com', role: 'member' }
, { id: 2, name: 'aaron', email: 'aaron.heckmann+github@gmail.com', role: 'admin' }
];
function loadUser(req, res, next) {
// You would fetch your user from the db
var | {
"filepath": "examples/route-middleware/index.js",
"language": "javascript",
"file_size": 2399,
"cut_index": 563,
"middle_length": 229
} |
/**
* Module dependencies.
*/
var express = require('../../');
var app = module.exports = express();
var logger = require('morgan');
var cookieParser = require('cookie-parser');
// custom log format
if (process.env.NODE_ENV !== 'test') app.use(logger(':method :url'))
// parses request cookies, populating
// req.... | checkbox" name="remember"/> remember me</label> '
+ '<input type="submit" value="Submit"/>.</p></form>');
}
});
app.get('/forget', function(req, res){
res.clearCookie('remember');
res.redirect(req.get('Referrer') || '/');
});
app.post('/', fu | d())
app.get('/', function(req, res){
if (req.cookies.remember) {
res.send('Remembered :). Click to <a href="/forget">forget</a>!.');
} else {
res.send('<form method="post"><p>Check to <label>'
+ '<input type=" | {
"filepath": "examples/cookies/index.js",
"language": "javascript",
"file_size": 1311,
"cut_index": 524,
"middle_length": 229
} |
e strict'
/**
* Module dependencies.
*/
var https = require('node:https');
var path = require('node:path');
var extname = path.extname;
/**
* Expose `GithubView`.
*/
module.exports = GithubView;
/**
* Custom view that fetches and renders
* remove github templates. You could
* render templates from a databas... | {
host: 'raw.githubusercontent.com',
port: 443,
path: this.path,
method: 'GET'
};
https.request(opts, function(res) {
var buf = '';
res.setEncoding('utf8');
res.on('data', function(str){ buf += str });
res.on('end', fun | ver
// in your own implementation you could ignore this
this.path = '/' + options.root + '/master/' + name;
}
/**
* Render the view.
*/
GithubView.prototype.render = function(options, fn){
var self = this;
var opts = | {
"filepath": "examples/view-constructor/github-view.js",
"language": "javascript",
"file_size": 1069,
"cut_index": 515,
"middle_length": 229
} |
'use strict'
/**
* Module dependencies.
*/
var escapeHtml = require('escape-html');
var express = require('../..');
var fs = require('node:fs');
var marked = require('marked');
var path = require('node:path');
var app = module.exports = express();
// register .md as an engine in express view system
app.engine('m... | q, res){
res.render('index', { title: 'Markdown Example' });
});
app.get('/fail', function(req, res){
res.render('missing', { title: 'Markdown Example' });
});
/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console.log('Expres | return escapeHtml(options[name] || '');
});
fn(null, html);
});
});
app.set('views', path.join(__dirname, 'views'));
// make it the default, so we don't need .md
app.set('view engine', 'md');
app.get('/', function(re | {
"filepath": "examples/markdown/index.js",
"language": "javascript",
"file_size": 1025,
"cut_index": 512,
"middle_length": 229
} |
e:path');
var User = require('./user');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// filter ferrets only
function ferrets(user) {
return user.species === 'ferret'
}
// naive nesting approach,
// delegating errors to next(err)
// in order to expose the "co... | able
// on the request object
function count(req, res, next) {
User.count(function(err, count){
if (err) return next(err);
req.count = count;
next();
})
}
function users(req, res, next) {
User.all(function(err, users){
if (err) retu | xt(err);
res.render('index', {
title: 'Users',
count: count,
users: users.filter(ferrets)
});
})
})
});
// this approach is cleaner,
// less nesting and we have
// the variables avail | {
"filepath": "examples/view-locals/index.js",
"language": "javascript",
"file_size": 3127,
"cut_index": 614,
"middle_length": 229
} |
./utils').methods;
var compileETag = require('./utils').compileETag;
var compileQueryParser = require('./utils').compileQueryParser;
var compileTrust = require('./utils').compileTrust;
var resolve = require('node:path').resolve;
var once = require('once')
var Router = require('router');
/**
* Module variables.
* @pr... | tion methods
*
* @private
*/
app.init = function init() {
var router = null;
this.cache = Object.create(null);
this.engines = Object.create(null);
this.settings = Object.create(null);
this.defaultConfiguration();
// Setup getting to lazi | inheritance back-compat
* @private
*/
var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
/**
* Initialize the server.
*
* - setup default configuration
* - setup default middleware
* - setup route reflec | {
"filepath": "lib/application.js",
"language": "javascript",
"file_size": 13977,
"cut_index": 921,
"middle_length": 229
} |
require('range-parser');
var parse = require('parseurl');
var proxyaddr = require('proxy-addr');
/**
* Request prototype.
* @public
*/
var req = Object.create(http.IncomingMessage.prototype)
/**
* Module exports.
* @public
*/
module.exports = req
/**
* Return request header.
*
* The `Referrer` header fie... | e) {
throw new TypeError('name argument is required to req.get');
}
if (typeof name !== 'string') {
throw new TypeError('name must be a string to req.get');
}
var lc = name.toLowerCase();
switch (lc) {
case 'referer':
case 'ref | // => "text/plain"
*
* req.get('Something');
* // => undefined
*
* Aliased as `req.header()`.
*
* @param {String} name
* @return {String}
* @public
*/
req.get =
req.header = function header(name) {
if (!nam | {
"filepath": "lib/request.js",
"language": "javascript",
"file_size": 12254,
"cut_index": 921,
"middle_length": 229
} |
ODS } = require('node:http');
var contentType = require('content-type');
var etag = require('etag');
var mime = require('mime-types')
var proxyaddr = require('proxy-addr');
var qs = require('qs');
var querystring = require('node:querystring');
const { Buffer } = require('node:buffer');
/**
* A list of lowercased HTT... | ]
* @return {String}
* @api private
*/
exports.wetag = createETagGenerator({ weak: true })
/**
* Normalize the given `type`, for example "html" becomes "text/html".
*
* @param {String} type
* @return {Object}
* @api private
*/
exports.normalize | } body
* @param {String} [encoding]
* @return {String}
* @api private
*/
exports.etag = createETagGenerator({ weak: false })
/**
* Return weak ETag for `body`.
*
* @param {String|Buffer} body
* @param {String} [encoding | {
"filepath": "lib/utils.js",
"language": "javascript",
"file_size": 5293,
"cut_index": 716,
"middle_length": 229
} |
'use strict'
// install redis first:
// https://redis.io/
// then:
// $ npm install redis online
// $ redis-server
/**
* Module dependencies.
*/
var express = require('../..');
var online = require('online');
var redis = require('redis');
var db = redis.createClient();
// online
online = online(db);
// app
va... | req, res, next){
online.last(5, function(err, ids){
if (err) return next(err);
res.send('<p>Users online: ' + ids.length + '</p>' + list(ids));
});
});
/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console.log('Express | ser-agent']);
next();
});
/**
* List helper.
*/
function list(ids) {
return '<ul>' + ids.map(function(id){
return '<li>' + id + '</li>';
}).join('') + '</ul>';
}
/**
* GET users online.
*/
app.get('/', function( | {
"filepath": "examples/online/index.js",
"language": "javascript",
"file_size": 1024,
"cut_index": 512,
"middle_length": 229
} |
('./utils').setCharset;
var cookie = require('cookie');
var send = require('send');
var extname = path.extname;
var resolve = path.resolve;
var vary = require('vary');
const { Buffer } = require('node:buffer');
/**
* Response prototype.
* @public
*/
var res = Object.create(http.ServerResponse.prototype)
/**
* Mo... | code` is not an integer.
* @throws {RangeError} If `code` is outside the range 100 to 999.
* @public
*/
res.status = function status(code) {
// Check if the status code is not an integer
if (!Number.isInteger(code)) {
throw new TypeError(`Inval | ovided status code is not an integer or if it's outside the allowable range.
*
* @param {number} code - The HTTP status code to set.
* @return {ServerResponse} - Returns itself for chaining methods.
* @throws {TypeError} If ` | {
"filepath": "lib/response.js",
"language": "javascript",
"file_size": 24844,
"cut_index": 1331,
"middle_length": 229
} |
ht(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
var bodyParser = require('body-parser')
var EventEmitter = require('node:events').EventEmitter;
var mixin = require('merge-descript... |
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
// expose the prototype that will get set on requests
app.request = Object.create(req, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
/ | = module.exports = createApplication;
/**
* Create an express application.
*
* @return {Function}
* @api public
*/
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
}; | {
"filepath": "lib/express.js",
"language": "javascript",
"file_size": 1636,
"cut_index": 537,
"middle_length": 229
} |
tion(){
it('should work without handlers', function(done) {
var req = { method: 'GET', url: '/' }
var route = new Route('/foo')
route.dispatch(req, {}, done)
})
it('should not stack overflow with a large sync stack', function (done) {
this.timeout(5000) // long-running test
var req = { metho... | return done(err)
assert.ok(req.called)
assert.strictEqual(req.counter, 6000)
done()
})
})
describe('.all', function(){
it('should add handler', function(done){
var req = { method: 'GET', url: '/' };
var route = n | l(function (req, res, next) {
req.counter++
next()
})
}
route.get(function (req, res, next) {
req.called = true
next()
})
route.dispatch(req, {}, function (err) {
if (err) | {
"filepath": "test/Route.js",
"language": "javascript",
"file_size": 6480,
"cut_index": 716,
"middle_length": 229
} |
sert(typeof router.handle === 'function')
assert(typeof router.use === 'function')
});
it('should support .use of other routers', function (done) {
var router = new Router();
var another = new Router();
another.get('/bar', function (req, res) {
res.end();
});
router.use('/foo', anoth... | od: 'GET' }, { end: done }, function () { });
});
it('should handle blank URL', function (done) {
var router = new Router();
router.use(function (req, res) {
throw new Error('should not be called')
});
router.handle({ url: '', | ar another = new Router();
another.get('/:bar', function (req, res) {
assert.strictEqual(req.params.bar, 'route')
res.end();
});
router.use('/:foo', another);
router.handle({ url: '/test/route', meth | {
"filepath": "test/Router.js",
"language": "javascript",
"file_size": 17372,
"cut_index": 921,
"middle_length": 229
} |
var express = require('../');
var request = require('supertest');
var assert = require('node:assert');
describe('HEAD', function(){
it('should default to GET', function(done){
var app = express();
app.get('/tobi', function(req, res){
// send() detects HEAD
res.send('tobi');
});
reques... | get('/tobi')
.expect(200, function(err, res){
if (err) return done(err);
delete headers.date;
delete res.headers.date;
assert.deepEqual(res.headers, headers);
done();
});
});
})
})
describe('app.he | {
// send() detects HEAD
res.send('tobi');
});
request(app)
.head('/tobi')
.expect(200, function(err, res){
if (err) return done(err);
var headers = res.headers;
request(app)
. | {
"filepath": "test/app.head.js",
"language": "javascript",
"file_size": 1412,
"cut_index": 524,
"middle_length": 229
} |
ar express = require('..')
var request = require('supertest')
describe('app', function(){
it('should inherit from event emitter', function(done){
var app = express();
app.on('foo', done);
app.emit('foo');
})
it('should be callable', function(){
var app = express();
assert.equal(typeof app, '... | sert.strictEqual(blog.parent, app)
assert.strictEqual(blogAdmin.parent, blog)
})
})
describe('app.mountpath', function(){
it('should return the mounted path', function(){
var admin = express();
var app = express();
var blog = express() | the parent when mounted', function(){
var app = express()
, blog = express()
, blogAdmin = express();
app.use('/blog', blog);
blog.use('/admin', blogAdmin);
assert(!app.parent, 'app.parent');
as | {
"filepath": "test/app.js",
"language": "javascript",
"file_size": 2738,
"cut_index": 563,
"middle_length": 229
} |
se strict'
var after = require('after')
var express = require('../')
, request = require('supertest');
describe('app.all()', function(){
it('should add a router per method', function(done){
var app = express();
var cb = after(2, done)
app.all('/tobi', function(req, res){
res.end(req.method);
... | ction(done){
var app = express()
, n = 0;
app.all('/*splat', function(req, res, next){
if (n++) return done(new Error('DELETE called several times'));
next();
});
request(app)
.del('/tobi')
.expect(404, done);
| ust once', fun | {
"filepath": "test/app.all.js",
"language": "javascript",
"file_size": 790,
"cut_index": 514,
"middle_length": 14
} |
= require('../')
var assert = require('node:assert')
describe('app.listen()', function(){
it('should wrap with an HTTP server', function(done){
var app = express();
var server = app.listen(0, function () {
server.close(done)
});
})
it('should callback on HTTP server errors', function (done) {... | .1', 5, function () {
const { address, port } = server.address();
assert.strictEqual(address, '127.0.0.1');
assert(Number.isInteger(port) && port > 0);
// backlog isn’t directly inspectable, but if no error was thrown
// we kn | rt(err.code === 'EADDRINUSE')
server1.close()
done()
})
})
})
it('accepts port + hostname + backlog + callback', function (done) {
const app = express();
const server = app.listen(0, '127.0.0 | {
"filepath": "test/app.listen.js",
"language": "javascript",
"file_size": 1713,
"cut_index": 537,
"middle_length": 229
} |
ar express = require('../')
, fs = require('node:fs');
var path = require('node:path')
function render(path, options, fn) {
fs.readFile(path, 'utf8', function(err, str){
if (err) return fn(err);
str = str.replace('{{user.name}}', options.user.name);
fn(null, str);
});
}
describe('app', function(){
... | })
it('should throw when the callback is missing', function(){
var app = express();
assert.throws(function () {
app.engine('.html', null);
}, /callback function required/)
})
it('should work without leading "."', fun | engine('.html', render);
app.locals.user = { name: 'tobi' };
app.render('user.html', function(err, str){
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
| {
"filepath": "test/app.engine.js",
"language": "javascript",
"file_size": 2246,
"cut_index": 563,
"middle_length": 229
} |
var app = express();
app.param(['id', 'uid'], function(req, res, next, id){
id = Number(id);
if (isNaN(id)) return next('route');
req.params.id = id;
next();
});
app.get('/post/:id', function(req, res){
var id = req.params.id;
res.send((typeof id) + '... | name, fn)', function(){
it('should map logic for a single param', function(done){
var app = express();
app.param('id', function(req, res, next, id){
id = Number(id);
if (isNaN(id)) return next('route');
req.params.i | 23')
.expect(200, 'number:123', function (err) {
if (err) return done(err)
request(app)
.get('/post/123')
.expect('number:123', done)
})
})
})
describe('.param( | {
"filepath": "test/app.param.js",
"language": "javascript",
"file_size": 7560,
"cut_index": 716,
"middle_length": 229
} |
pl'), function (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should support absolute paths with "view engine"', function(done){
var app = createApp();
app.set('view engine', 'tmpl');
app.locals.user = { name: 't... | ion (err, str) {
if (err) return done(err);
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should support index.<engine>', function(done){
var app = createApp();
app.set('views', path.join(__dir | })
})
it('should expose app.locals', function(done){
var app = createApp();
app.set('views', path.join(__dirname, 'fixtures'))
app.locals.user = { name: 'tobi' };
app.render('user.tmpl', funct | {
"filepath": "test/app.render.js",
"language": "javascript",
"file_size": 11092,
"cut_index": 921,
"middle_length": 229
} |
function(){
it('should return a new route', function(done){
var app = express();
app.route('/foo')
.get(function(req, res) {
res.send('get');
})
.post(function(req, res) {
res.send('post');
});
request(app)
.post('/foo')
.expect('post', done);
});
it('should all... | .route('/:foo')
.get(function(req, res) {
res.send(req.params.foo);
});
request(app)
.get('/test')
.expect('test', done);
});
it('should not error on empty routes', function(done){
var app = express();
app.route('/: | ;
})
.post(function(req, res) {
res.send('post');
});
request(app)
.post('/foo')
.expect('post', done);
});
it('should support dynamic routes', function(done){
var app = express();
app | {
"filepath": "test/app.route.js",
"language": "javascript",
"file_size": 4762,
"cut_index": 614,
"middle_length": 229
} |
est = require('supertest');
describe('OPTIONS', function(){
it('should default to the routes defined', function(done){
var app = express();
app.post('/', function(){});
app.get('/users', function(req, res){});
app.put('/users', function(req, res){});
request(app)
.options('/users')
.exp... | expect(200, 'GET, HEAD, PUT', done);
})
it('should not be affected by app.all', function(done){
var app = express();
app.get('/', function(){});
app.get('/users', function(req, res){});
app.put('/users', function(req, res){});
app | on(){});
app.get('/users', function(req, res){});
app.put('/users', function(req, res){});
app.get('/users', function(req, res){});
request(app)
.options('/users')
.expect('Allow', 'GET, HEAD, PUT')
. | {
"filepath": "test/app.options.js",
"language": "javascript",
"file_size": 2845,
"cut_index": 563,
"middle_length": 229
} |
ess = require('../')
, request = require('supertest');
describe('app', function(){
describe('.response', function(){
it('should extend the response prototype', function(done){
var app = express();
app.response.shout = function(str){
this.send(str.toUpperCase());
};
app.use(fun... | res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/')
.expect(200, 'FOO', cb)
request(app2)
.get('/')
.expect(500, /(?:not a function|has | {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app1.get('/', function (req, res) {
| {
"filepath": "test/app.response.js",
"language": "javascript",
"file_size": 2973,
"cut_index": 563,
"middle_length": 229
} |
.get('/user/1')
.expect('x-router', 'undefined')
.expect('x-user-id', '1')
.expect(200, '1', done);
})
describe('methods', function () {
methods.forEach(function (method) {
if (method === 'connect') return;
it('should include ' + method.toUpperCase(), function (done) {
... | s(app[method].bind(app, '/', 3), /argument handler must be a function/);
})
});
it('should re-route when method is altered', function (done) {
var app = express();
var cb = after(3, done);
app.use(function (req, res, next) | es.send(method)
});
request(app)
[method]('/foo')
.expect(200, done)
})
it('should reject numbers for app.' + method, function () {
var app = express();
assert.throw | {
"filepath": "test/app.router.js",
"language": "javascript",
"file_size": 29831,
"cut_index": 1331,
"middle_length": 229
} |
ess = require('../')
, request = require('supertest');
describe('app', function(){
describe('.request', function(){
it('should extend the request prototype', function(done){
var app = express();
app.request.querystring = function(){
return require('node:url').parse(this.url).query;
}... | function (req, res) {
res.send(req.foobar())
})
app2.get('/', function (req, res) {
res.send(req.foobar())
})
request(app1)
.get('/')
.expect(200, 'tobi', cb)
request(app2)
.get('/') | y extend for the referenced app', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.request.foobar = function () {
return 'tobi'
}
app1.get('/', | {
"filepath": "test/app.request.js",
"language": "javascript",
"file_size": 2983,
"cut_index": 563,
"middle_length": 229
} |
p = express();
app.set('foo', 'bar');
assert.equal(app.get('foo'), 'bar');
})
it('should set prototype values', function () {
var app = express()
app.set('hasOwnProperty', 42)
assert.strictEqual(app.get('hasOwnProperty'), 42)
})
it('should return the app', function () {
... | or prototype values', function () {
var app = express()
assert.strictEqual(app.set('hasOwnProperty'), undefined)
})
describe('"etag"', function(){
it('should throw on bad value', function(){
var app = express();
a | .set('foo', undefined), app);
})
it('should return set value', function () {
var app = express()
app.set('foo', 'bar')
assert.strictEqual(app.set('foo'), 'bar')
})
it('should return undefined f | {
"filepath": "test/config.js",
"language": "javascript",
"file_size": 5823,
"cut_index": 716,
"middle_length": 229
} |
nt-Type', 'application/json')
.set('Transfer-Encoding', 'chunked')
.expect(200, '{}', done)
})
it('should handle no message-body', function (done) {
request(createApp())
.post('/')
.set('Content-Type', 'application/json')
.unset('Transfer-Encoding')
.expect(200, '{}', done)
... | app.use(function (req, res, next) {
req.headers['content-length'] = '20' // bad length
next()
})
app.use(express.json())
app.post('/', function (req, res) {
res.json(req.body)
})
request(app)
.post('/')
| t('Content-Type', 'application/json')
.send(' \n')
.expect(400, '[entity.parse.failed] ' + parseError(' \n'), done)
})
it('should 400 when invalid content-length', function (done) {
var app = express()
| {
"filepath": "test/express.json.js",
"language": "javascript",
"file_size": 23675,
"cut_index": 1331,
"middle_length": 229
} |
/)
})
it('should serve static files', function (done) {
request(this.app)
.get('/todo.txt')
.expect(200, '- groceries', done)
})
it('should support nesting', function (done) {
request(this.app)
.get('/users/tobi.txt')
.expect(200, 'ferret', done)
})
... | function (done) {
request(this.app)
.get('/todo.txt')
.expect('Cache-Control', 'public, max-age=0')
.expect(200, done)
})
it('should support urlencoded pathnames', function (done) {
request(this.app)
.g | )
it('should set Last-Modified', function (done) {
request(this.app)
.get('/todo.txt')
.expect('Last-Modified', /\d{2} \w{3} \d{4}/)
.expect(200, done)
})
it('should default max-age=0', | {
"filepath": "test/express.static.js",
"language": "javascript",
"file_size": 23498,
"cut_index": 1331,
"middle_length": 229
} |
p.post('/', function (req, res) {
res.json(req.body)
})
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('str=')
.expect(400, /content length/, done)
})
it('should handle Content-Length: 0', function (done) {
request(this.app)
... | '{}', done)
})
it('should handle duplicated middleware', function (done) {
var app = express()
app.use(express.urlencoded())
app.use(express.urlencoded())
app.post('/', function (req, res) {
res.json(req.body)
})
reque | age-body', function (done) {
request(createApp({ limit: '1kb' }))
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Transfer-Encoding', 'chunked')
.send('')
.expect(200, | {
"filepath": "test/express.urlencoded.js",
"language": "javascript",
"file_size": 26741,
"cut_index": 1331,
"middle_length": 229
} |
be('.use(app)', function(){
it('should mount the app', function(done){
var blog = express()
, app = express();
blog.get('/blog', function(req, res){
res.end('blog');
});
app.use(blog);
request(app)
.get('/blog')
.expect('blog', done);
})
it('shou... | .expect(200, 'blog', cb)
request(app)
.get('/forum')
.expect(200, 'forum', cb)
})
it('should set the child\'s .parent', function(){
var blog = express()
, app = express();
app.use('/blog', blog);
a | ){
res.end('blog');
});
forum.get('/', function(req, res){
res.end('forum');
});
app.use('/blog', blog);
app.use('/forum', forum);
request(app)
.get('/blog')
| {
"filepath": "test/app.use.js",
"language": "javascript",
"file_size": 12605,
"cut_index": 921,
"middle_length": 229
} |
.post('/')
.set('Content-Type', 'application/octet-stream')
.send('the user is tobi')
.expect(200, { buf: '746865207573657220697320746f6269' }, done)
})
it('should 400 when invalid content-length', function (done) {
var app = express()
app.use(function (req, res, next) {
req... | nt length/, done)
})
it('should handle Content-Length: 0', function (done) {
request(this.app)
.post('/')
.set('Content-Type', 'application/octet-stream')
.set('Content-Length', '0')
.expect(200, { buf: '' }, done)
})
| ({ buf: req.body.toString('hex') })
} else {
res.json(req.body)
}
})
request(app)
.post('/')
.set('Content-Type', 'application/octet-stream')
.send('stuff')
.expect(400, /conte | {
"filepath": "test/express.raw.js",
"language": "javascript",
"file_size": 16296,
"cut_index": 921,
"middle_length": 229
} |
use strict'
var assert = require('node:assert')
var express = require('../');
var request = require('supertest');
describe('middleware', function(){
describe('.next()', function(){
it('should behave like connect', function(done){
var app = express()
, calls = [];
app.use(function(req, res, ... | });
});
request(app)
.get('/')
.set('Content-Type', 'application/json')
.send('{"foo":"bar"}')
.expect('Content-Type', 'application/json')
.expect(function () { assert.deepEqual(calls, ['one', 'two']) })
| var buf = '';
res.setHeader('Content-Type', 'application/json');
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk });
req.on('end', function(){
res.end(buf);
| {
"filepath": "test/middleware.basic.js",
"language": "javascript",
"file_size": 1051,
"cut_index": 513,
"middle_length": 229
} |
ar express = require('../');
var request = require('supertest');
describe('exports', function(){
it('should expose Router', function(){
assert.strictEqual(typeof express.Router, 'function')
})
it('should expose json middleware', function () {
assert.equal(typeof express.json, 'function')
assert.equa... | , 'function')
assert.equal(express.text.length, 1)
})
it('should expose urlencoded middleware', function () {
assert.equal(typeof express.urlencoded, 'function')
assert.equal(express.urlencoded.length, 1)
})
it('should expose the appl | xpose static middleware', function () {
assert.equal(typeof express.static, 'function')
assert.equal(express.static.length, 2)
})
it('should expose text middleware', function () {
assert.equal(typeof express.text | {
"filepath": "test/exports.js",
"language": "javascript",
"file_size": 2344,
"cut_index": 563,
"middle_length": 229
} |
/')
.set('Content-Type', 'text/plain')
.send('user is tobi')
.expect(200, '"user is tobi"', done)
})
it('should 400 when invalid content-length', function (done) {
var app = express()
app.use(function (req, res, next) {
req.headers['content-length'] = '20' // bad length
next(... | et('Content-Length', '0')
.expect(200, '""', done)
})
it('should handle empty message-body', function (done) {
request(createApp({ limit: '1kb' }))
.post('/')
.set('Content-Type', 'text/plain')
.set('Transfer-Encoding', 'ch | .send('user')
.expect(400, /content length/, done)
})
it('should handle Content-Length: 0', function (done) {
request(createApp({ limit: '1kb' }))
.post('/')
.set('Content-Type', 'text/plain')
.s | {
"filepath": "test/express.text.js",
"language": "javascript",
"file_size": 17277,
"cut_index": 921,
"middle_length": 229
} |
= require('../')
, request = require('supertest');
describe('req', function(){
describe('.acceptsCharsets(type)', function(){
describe('when Accept-Charset is not present', function(){
it('should return true', function(done){
var app = express();
app.use(function(req, res, next){
... | request(app)
.get('/')
.set('Accept-Charset', 'foo, bar, utf-8')
.expect('yes', done);
})
it('should return false otherwise', function(done){
var app = express();
app.use(function(req, res, next){
| s present', function () {
it('should return true', function (done) {
var app = express();
app.use(function(req, res, next){
res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no');
});
| {
"filepath": "test/req.acceptsCharsets.js",
"language": "javascript",
"file_size": 1609,
"cut_index": 537,
"middle_length": 229
} |
var express = require('../')
, request = require('supertest');
describe('req', function(){
describe('.acceptsLanguages', function(){
it('should return language if accepted', function (done) {
var app = express();
app.get('/', function (req, res) {
res.send({
'en-us': req.accept... | uages('es')
})
})
request(app)
.get('/')
.set('Accept-Language', 'en;q=.5, en-us')
.expect(200, { es: false }, done)
})
describe('when Accept-Language is not present', function(){
it('should alway | 'en-us': 'en-us', en: 'en' }, done)
})
it('should be false if language not accepted', function(done){
var app = express();
app.get('/', function (req, res) {
res.send({
es: req.acceptsLang | {
"filepath": "test/req.acceptsLanguages.js",
"language": "javascript",
"file_size": 1425,
"cut_index": 524,
"middle_length": 229
} |
= require('../')
, request = require('supertest');
describe('req', function(){
describe('.fresh', function(){
it('should return true when the resource is not modified', function(done){
var app = express();
var etag = '"12345"';
app.use(function(req, res){
res.set('ETag', etag);
... | "')
.expect(200, 'false', done);
})
it('should return false without response headers', function(done){
var app = express();
app.disable('x-powered-by')
app.use(function(req, res){
res.send(req.fresh);
});
| fied', function(done){
var app = express();
app.use(function(req, res){
res.set('ETag', '"123"');
res.send(req.fresh);
});
request(app)
.get('/')
.set('If-None-Match', '"12345 | {
"filepath": "test/req.fresh.js",
"language": "javascript",
"file_size": 1664,
"cut_index": 537,
"middle_length": 229
} |
n(){
describe('.host', function(){
it('should return the Host when present', function(done){
var app = express();
app.use(function(req, res){
res.end(req.host);
});
request(app)
.post('/')
.set('Host', 'example.com')
.expect('example.com', done);
})
it(... | null;
res.end(String(req.host));
});
request(app)
.post('/')
.expect('undefined', done);
})
it('should work with IPv6 Host', function(done){
var app = express();
app.use(function(req, res){
re | Host', 'example.com:3000')
.expect(200, 'example.com:3000', done);
})
it('should return undefined otherwise', function(done){
var app = express();
app.use(function(req, res){
req.headers.host = | {
"filepath": "test/req.host.js",
"language": "javascript",
"file_size": 3536,
"cut_index": 614,
"middle_length": 229
} |
est = require('supertest');
describe('req', function(){
describe('.ip', function(){
describe('when X-Forwarded-For is present', function(){
describe('when "trust proxy" is enabled', function(){
it('should return the client addr', function(done){
var app = express();
app.enable(... | .use(function(req, res, next){
res.send(req.ip);
});
request(app)
.get('/')
.set('X-Forwarded-For', 'client, p1, p2')
.expect('p1', done);
})
it('should return the addr after t | p1, p2')
.expect('client', done);
})
it('should return the addr after trusted proxy based on count', function (done) {
var app = express();
app.set('trust proxy', 2);
app | {
"filepath": "test/req.ip.js",
"language": "javascript",
"file_size": 2979,
"cut_index": 563,
"middle_length": 229
} |
ction () {
describe('when given a mime type', function () {
it('should return the type when matching', function (done) {
var app = express()
app.use(function (req, res) {
res.json(req.is('application/json'))
})
request(app)
.post('/')
.type('application/json')
.... |
var app = express()
app.use(function (req, res) {
res.json(req.is('application/json'))
})
request(app)
.post('/')
.type('application/json; charset=UTF-8')
.send('{}')
.expect(200, '"application/jso | {
res.json(req.is('image/jpeg'))
})
request(app)
.post('/')
.type('application/json')
.send('{}')
.expect(200, 'false', done)
})
it('should ignore charset', function (done) { | {
"filepath": "test/req.is.js",
"language": "javascript",
"file_size": 3782,
"cut_index": 614,
"middle_length": 229
} |
rtest');
describe('req', function(){
describe('.acceptsEncodings', function () {
it('should return encoding if accepted', function (done) {
var app = express();
app.get('/', function (req, res) {
res.send({
gzip: req.acceptsEncodings('gzip'),
deflate: req.acceptsEncodings... | function(done){
var app = express();
app.get('/', function (req, res) {
res.send({
bogus: req.acceptsEncodings('bogus')
})
})
request(app)
.get('/')
.set('Accept-Encoding', ' gzip, deflate |
it('should be false if encoding not accepted', | {
"filepath": "test/req.acceptsEncodings.js",
"language": "javascript",
"file_size": 953,
"cut_index": 582,
"middle_length": 52
} |
var express = require('../')
, request = require('supertest')
, assert = require('node:assert');
describe('req', function(){
describe('.get(field)', function(){
it('should return the header field value', function(done){
var app = express();
app.use(function(req, res){
assert(req.get('S... | .set('Referrer', 'http://foobar.com')
.expect('http://foobar.com', done);
})
it('should throw missing header name', function (done) {
var app = express()
app.use(function (req, res) {
res.end(req.get())
})
| on/json', done);
})
it('should special-case Referer', function(done){
var app = express();
app.use(function(req, res){
res.end(req.get('Referer'));
});
request(app)
.post('/')
| {
"filepath": "test/req.get.js",
"language": "javascript",
"file_size": 1415,
"cut_index": 524,
"middle_length": 229
} |
= require('../')
, request = require('supertest');
describe('req', function(){
describe('.ips', function(){
describe('when X-Forwarded-For is present', function(){
describe('when "trust proxy" is enabled', function(){
it('should return an array of the specified addresses', function(done){
... | 'trust proxy', 2);
app.use(function(req, res, next){
res.send(req.ips);
});
request(app)
.get('/')
.set('X-Forwarded-For', 'client, p1, p2')
.expect('["p1","p2"]', done);
})
| '/')
.set('X-Forwarded-For', 'client, p1, p2')
.expect('["client","p1","p2"]', done);
})
it('should stop at first untrusted', function(done){
var app = express();
app.set( | {
"filepath": "test/req.ips.js",
"language": "javascript",
"file_size": 1743,
"cut_index": 537,
"middle_length": 229
} |
st = require('supertest')
describe('req', function(){
describe('.baseUrl', function(){
it('should be empty for top-level route', function(done){
var app = express()
app.get('/:a', function(req, res){
res.end(req.baseUrl)
})
request(app)
.get('/foo')
.expect(200, '', ... | ss.Router()
var sub2 = express.Router()
var sub3 = express.Router()
sub3.get('/:d', function(req, res){
res.end(req.baseUrl)
})
sub2.use('/:c', sub3)
sub1.use('/:b', sub2)
app.use('/:a', sub1)
reque | rl)
})
app.use('/:a', sub)
request(app)
.get('/foo/bar')
.expect(200, '/foo', done);
})
it('should contain full lower path', function(done){
var app = express()
var sub1 = expre | {
"filepath": "test/req.baseUrl.js",
"language": "javascript",
"file_size": 2120,
"cut_index": 563,
"middle_length": 229
} |
n(){
describe('.hostname', function(){
it('should return the Host when present', function(done){
var app = express();
app.use(function(req, res){
res.end(req.hostname);
});
request(app)
.post('/')
.set('Host', 'example.com')
.expect('example.com', done);
})
... | = null;
res.end(String(req.hostname));
});
request(app)
.post('/')
.expect('undefined', done);
})
it('should work with IPv6 Host', function(done){
var app = express();
app.use(function(req, res){
| .set('Host', 'example.com:3000')
.expect('example.com', done);
})
it('should return undefined otherwise', function(done){
var app = express();
app.use(function(req, res){
req.headers.host | {
"filepath": "test/req.hostname.js",
"language": "javascript",
"file_size": 4420,
"cut_index": 614,
"middle_length": 229
} |
= require('..');
var request = require('supertest');
describe('res', function(){
describe('.links(obj)', function(){
it('should set Link header field', function (done) {
var app = express();
app.use(function (req, res) {
res.links({
next: 'http://api.example.com/users?page=2',
... | res) {
res.links({
next: 'http://api.example.com/users?page=2',
last: 'http://api.example.com/users?page=5'
});
res.links({
prev: 'http://api.example.com/users?page=1'
});
res.end();
| l="next", <http://api.example.com/users?page=5>; rel="last"')
.expect(200, done);
})
it('should set Link header field for multiple calls', function (done) {
var app = express();
app.use(function (req, | {
"filepath": "test/res.links.js",
"language": "javascript",
"file_size": 1877,
"cut_index": 537,
"middle_length": 229
} |
s = require('../lib/utils');
describe('utils.etag(body, encoding)', function(){
it('should support strings', function(){
assert.strictEqual(utils.etag('express!'),
'"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"')
})
it('should support utf8 strings', function(){
assert.strictEqual(utils.etag('express❤', 'utf8'),... | with a malformed parameter and break the loop in acceptParams', () => {
const result = utils.normalizeType('text/plain;invalid');
assert.deepEqual(result,{
value: 'text/plain',
quality: 1,
params: {} // No parameters are added sin | })
it('should support empty string', function(){
assert.strictEqual(utils.etag(''),
'"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"')
})
})
describe('utils.normalizeType acceptParams method', () => {
it('should handle a type | {
"filepath": "test/utils.js",
"language": "javascript",
"file_size": 3768,
"cut_index": 614,
"middle_length": 229
} |
rvice', function(){
describe('GET /api/users', function(){
describe('without an api key', function(){
it('should respond with 400 bad request', function(done){
request(app)
.get('/api/users')
.expect(400, done);
})
})
describe('with an invalid api key', function(){
... | {"name":"tobi"},{"name":"loki"},{"name":"jane"}]', done)
})
})
})
describe('GET /api/repos', function(){
describe('without an api key', function(){
it('should respond with 400 bad request', function(done){
request(app)
| id api key', function(){
it('should respond users json', function(done){
request(app)
.get('/api/users?api-key=foo')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, '[ | {
"filepath": "test/acceptance/web-service.js",
"language": "javascript",
"file_size": 3129,
"cut_index": 614,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.