• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang echo.NewContext函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/labstack/echo.NewContext函数的典型用法代码示例。如果您正苦于以下问题:Golang NewContext函数的具体用法?Golang NewContext怎么用?Golang NewContext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewContext函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestIsAjax

func TestIsAjax(t *testing.T) {
	e := echo.New()
	req, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Error(err)
	}
	res := httptest.NewRecorder()
	ctx := echo.NewContext(req, echo.NewResponse(res), e)

	if ok := IsAjax(ctx); ok {
		t.Errorf("expected false got %v", ok)
	}

	req1, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Error(err)
	}
	req1.Header.Set("X-Requested-With", "XMLHttpRequest")
	res1 := httptest.NewRecorder()
	ctx1 := echo.NewContext(req1, echo.NewResponse(res1), e)

	if ok := IsAjax(ctx1); !ok {
		t.Errorf("expected true got %v", ok)
	}
}
开发者ID:jwulf,项目名称:zedlist,代码行数:25,代码来源:utils_test.go


示例2: TestGzip

func TestGzip(t *testing.T) {
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	h := func(c *echo.Context) error {
		c.Response().Write([]byte("test")) // Content-Type sniffing
		return nil
	}

	// Skip if no Accept-Encoding header
	Gzip()(h)(c)
	assert.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, "test", rec.Body.String())

	req, _ = http.NewRequest(echo.GET, "/", nil)
	req.Header.Set(echo.AcceptEncoding, "gzip")
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), echo.New())

	// Gzip
	Gzip()(h)(c)
	assert.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, "gzip", rec.Header().Get(echo.ContentEncoding))
	assert.Contains(t, rec.Header().Get(echo.ContentType), echo.TextPlain)
	r, err := gzip.NewReader(rec.Body)
	defer r.Close()
	if assert.NoError(t, err) {
		buf := new(bytes.Buffer)
		buf.ReadFrom(r)
		assert.Equal(t, "test", buf.String())
	}
}
开发者ID:alkhatib,项目名称:echo,代码行数:32,代码来源:compress_test.go


示例3: TestLogger

func TestLogger(t *testing.T) {
	// Note: Just for the test coverage, not a real test.
	e := echo.New()
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), e)

	// With X-Real-IP
	req.Header.Add(echo.XRealIP, "127.0.0.1")
	h := func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	Logger()(h)(c)

	// With X-Forwarded-For
	req.Header.Del(echo.XRealIP)
	req.Header.Add(echo.XForwardedFor, "127.0.0.1")
	h = func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	Logger()(h)(c)

	// Status 2xx
	h = func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	Logger()(h)(c)

	// Status 3xx
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), e)
	h = func(c *echo.Context) error {
		return c.String(http.StatusTemporaryRedirect, "test")
	}
	Logger()(h)(c)

	// Status 4xx
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), e)
	h = func(c *echo.Context) error {
		return c.String(http.StatusNotFound, "test")
	}
	Logger()(h)(c)

	// Status 5xx with empty path
	req, _ = http.NewRequest(echo.GET, "", nil)
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), e)
	h = func(c *echo.Context) error {
		return errors.New("error")
	}
	Logger()(h)(c)
}
开发者ID:jameswei,项目名称:kingtask,代码行数:53,代码来源:logger_test.go


示例4: TestStripTrailingSlash

func TestStripTrailingSlash(t *testing.T) {
	req, _ := http.NewRequest(echo.GET, "/users/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	StripTrailingSlash()(c)
	assert.Equal(t, "/users", c.Request().URL.Path)
}
开发者ID:alkhatib,项目名称:echo,代码行数:7,代码来源:slash_test.go


示例5: TestListRegions

func TestListRegions(t *testing.T) {
	for _, test := range []struct {
		p    mockProvisioner
		err  error
		code int
		body string
	}{
		{
			createProvisioner([]provisioner.Region{}),
			nil,
			200,
			"[]",
		},
		{
			createProvisioner([]provisioner.Region{{"name", "description", "country"}}),
			nil,
			200,
			"[{\"name\":\"name\",\"description\":\"description\",\"country\":\"country\"}]",
		},
	} {
		s := &yovpnServer{test.p}

		e := echo.New()
		req := mustNewRequest("GET", "/regions", nil)
		w := httptest.NewRecorder()
		c := echo.NewContext(req, echo.NewResponse(w, e), e)
		err := s.getRegions(c)

		assert.Equal(t, test.err, err)
		assert.Equal(t, test.code, w.Code)
		assert.Equal(t, test.body, w.Body.String())
	}
}
开发者ID:xperimental,项目名称:yovpn,代码行数:33,代码来源:web_test.go


示例6: TestLoggerIPAddress

func TestLoggerIPAddress(t *testing.T) {
	e := echo.New()
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec, e), e)
	buf := new(bytes.Buffer)
	e.Logger().SetOutput(buf)
	ip := "127.0.0.1"
	h := func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}

	mw := Logger()

	// With X-Real-IP
	req.Header.Add(echo.XRealIP, ip)
	mw(h)(c)
	assert.Contains(t, buf.String(), ip)

	// With X-Forwarded-For
	buf.Reset()
	req.Header.Del(echo.XRealIP)
	req.Header.Add(echo.XForwardedFor, ip)
	mw(h)(c)
	assert.Contains(t, buf.String(), ip)

	// with req.RemoteAddr
	buf.Reset()
	mw(h)(c)
	assert.Contains(t, buf.String(), ip)
}
开发者ID:prabirshrestha,项目名称:echo,代码行数:31,代码来源:logger_test.go


示例7: TestRedirectToSlash

func TestRedirectToSlash(t *testing.T) {
	req, _ := http.NewRequest(echo.GET, "/users", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	RedirectToSlash(RedirectToSlashOptions{Code: http.StatusTemporaryRedirect})(c)
	assert.Equal(t, http.StatusTemporaryRedirect, rec.Code)
	assert.Equal(t, "/users/", c.Response().Header().Get("Location"))
}
开发者ID:alkhatib,项目名称:echo,代码行数:8,代码来源:slash_test.go


示例8: TestSleep

func TestSleep(t *testing.T) {
	req, _ := http.NewRequest(echo.POST, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	start := time.Now()
	Sleep(1)(c)
	duration := time.Now().Sub(start)
	assert.True(t, duration > time.Second*1)

	req, _ = http.NewRequest(echo.GET, "/", nil)
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), echo.New())
	start = time.Now()
	Sleep(1)(c)
	duration = time.Now().Sub(start)
	assert.True(t, duration < 1*time.Second)
}
开发者ID:binarydud,项目名称:jumphash,代码行数:17,代码来源:server_test.go


示例9: TestData

func TestData(t *testing.T) {
	sampleData := []struct {
		key string
		val interface{}
	}{
		{"one", 1},
		{"two", "two"},
		{"three", "three"},
	}
	e := echo.New()
	req, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Error(err)
	}
	res := httptest.NewRecorder()

	// Create the context on which we will be messing with
	ctx := echo.NewContext(req, echo.NewResponse(res), e)

	//
	//	SetData
	//
	for _, v := range sampleData {
		SetData(ctx, v.key, v.val)
	}

	//
	//	GetData
	//
	data, ok := GetData(ctx).(Data)
	if !ok {
		t.Error("kaboom")
	}

	// Check the Data methods
	d := data.Get(sampleData[0].key)
	if d == nil {
		t.Errorf("expected %v got nil instead", sampleData[0].val)
	}

	data.Set("hello", "world")
	if h := data.Get("hello"); h != nil {
		if h.(string) != "world" {
			t.Errorf("expected world got %v", h)
		}
	}

	//
	//	GetLang
	//
	SetData(ctx, settings.LangDataKey, "en")

	lang := GetLang(ctx)
	if lang != "en" {
		t.Errorf("expected en got %s", lang)
	}
}
开发者ID:jwulf,项目名称:zedlist,代码行数:57,代码来源:utils_test.go


示例10: TestHash

func TestHash(t *testing.T) {
	e := echo.New()
	req, _ := http.NewRequest(echo.POST, "/", strings.NewReader("password=angryMonkey"))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded;")
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), e)
	Hash(c)
	assert.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, "ZEHhWB65gUlzdVwtDQArEyx+KVLzp/aTaRaPlBzYRIFj6vjFdqEb0Q5B8zVKCZ0vKbZPZklJz0Fd7su2A+gf7Q==", rec.Body.String())
}
开发者ID:binarydud,项目名称:jumphash,代码行数:10,代码来源:server_test.go


示例11: TestJWTAuth

func TestJWTAuth(t *testing.T) {
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	key := []byte("key")
	fn := func(kid string, method jwt.SigningMethod) ([]byte, error) {
		return key, nil
	}
	ja := JWTAuth(fn)
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims["foo"] = "bar"
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	ts, err := token.SignedString(key)
	assert.NoError(t, err)

	// Valid credentials
	auth := Bearer + " " + ts
	req.Header.Set(echo.Authorization, auth)
	assert.NoError(t, ja(c))

	//---------------------
	// Invalid credentials
	//---------------------

	// Expired token
	token.Claims["exp"] = time.Now().Add(-time.Second).Unix()
	ts, err = token.SignedString(key)
	assert.NoError(t, err)
	auth = Bearer + " " + ts
	req.Header.Set(echo.Authorization, auth)
	he := ja(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusUnauthorized, he.Code())

	// Empty Authorization header
	req.Header.Set(echo.Authorization, "")
	he = ja(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// Invalid Authorization header
	auth = "token"
	req.Header.Set(echo.Authorization, auth)
	he = ja(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// Invalid scheme
	auth = "Bear token"
	req.Header.Set(echo.Authorization, auth)
	he = ja(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// WebSocket
	c.Request().Header.Set(echo.Upgrade, echo.WebSocket)
	assert.NoError(t, ja(c))
}
开发者ID:alkhatib,项目名称:echo,代码行数:54,代码来源:auth_test.go


示例12: TestShutdown

func TestShutdown(t *testing.T) {
	sigchan := make(chan os.Signal, 1)
	signal.Notify(sigchan, os.Interrupt, os.Kill)
	e := echo.New()
	req, _ := http.NewRequest(echo.POST, "/", strings.NewReader("command=shutdown"))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded;")
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), e)
	Shutdown()(c)
	s := <-sigchan
	assert.Equal(t, os.Interrupt, s)

}
开发者ID:binarydud,项目名称:jumphash,代码行数:13,代码来源:server_test.go


示例13: TestRecover

func TestRecover(t *testing.T) {
	e := echo.New()
	e.SetDebug(true)
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), e)
	h := func(c *echo.Context) error {
		panic("test")
	}
	Recover()(h)(c)
	assert.Equal(t, http.StatusInternalServerError, rec.Code)
	assert.Contains(t, rec.Body.String(), "panic recover")
}
开发者ID:jameswei,项目名称:kingtask,代码行数:13,代码来源:recover_test.go


示例14: TestLogger

func TestLogger(t *testing.T) {
	// Note: Just for the test coverage, not a real test.
	e := echo.New()
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec, e), e)

	// Status 2xx
	h := func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	Logger()(h)(c)

	// Status 3xx
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec, e), e)
	h = func(c *echo.Context) error {
		return c.String(http.StatusTemporaryRedirect, "test")
	}
	Logger()(h)(c)

	// Status 4xx
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec, e), e)
	h = func(c *echo.Context) error {
		return c.String(http.StatusNotFound, "test")
	}
	Logger()(h)(c)

	// Status 5xx with empty path
	req, _ = http.NewRequest(echo.GET, "", nil)
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec, e), e)
	h = func(c *echo.Context) error {
		return errors.New("error")
	}
	Logger()(h)(c)
}
开发者ID:prabirshrestha,项目名称:echo,代码行数:38,代码来源:logger_test.go


示例15: TestLogger

func TestLogger(t *testing.T) {
	e := echo.New()
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), e)
	b := &bytes.Buffer{}

	// Status 2xx
	h := func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	Logger(b)(h)(c)

	// Status 3xx
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), e)
	h = func(c *echo.Context) error {
		return c.String(http.StatusTemporaryRedirect, "test")
	}
	Logger(b)(h)(c)

	// Status 4xx
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), e)
	h = func(c *echo.Context) error {
		return c.String(http.StatusNotFound, "test")
	}
	Logger(b)(h)(c)

	// Status 5xx with empty path
	req, _ = http.NewRequest(echo.GET, "", nil)
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), e)
	h = func(c *echo.Context) error {
		return errors.New("error")
	}
	Logger(b)(h)(c)
}
开发者ID:lestrrat,项目名称:go-echo-apachelog,代码行数:38,代码来源:apachelog_test.go


示例16: TestBasicAuth

func TestBasicAuth(t *testing.T) {
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	fn := func(u, p string) bool {
		if u == "joe" && p == "secret" {
			return true
		}
		return false
	}
	ba := BasicAuth(fn)

	// Valid credentials
	auth := Basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))
	req.Header.Set(echo.Authorization, auth)
	assert.NoError(t, ba(c))

	//---------------------
	// Invalid credentials
	//---------------------

	// Incorrect password
	auth = Basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:password"))
	req.Header.Set(echo.Authorization, auth)
	he := ba(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusUnauthorized, he.Code())

	// Empty Authorization header
	req.Header.Set(echo.Authorization, "")
	he = ba(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// Invalid Authorization header
	auth = base64.StdEncoding.EncodeToString([]byte(" :secret"))
	req.Header.Set(echo.Authorization, auth)
	he = ba(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// Invalid scheme
	auth = "Base " + base64.StdEncoding.EncodeToString([]byte(" :secret"))
	req.Header.Set(echo.Authorization, auth)
	he = ba(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// WebSocket
	c.Request().Header.Set(echo.Upgrade, echo.WebSocket)
	assert.NoError(t, ba(c))
}
开发者ID:alkhatib,项目名称:echo,代码行数:48,代码来源:auth_test.go


示例17: TestBlank

func TestBlank(t *testing.T) {
	e := echo.New()
	s := &yovpnServer{}
	req := mustNewRequest("GET", "/", nil)
	w := httptest.NewRecorder()

	c := echo.NewContext(req, echo.NewResponse(w, e), e)
	err := s.blank(c)

	if err != nil {
		t.Errorf("Expected no error, but got %s", err)
	}
	if w.Code != http.StatusOK {
		t.Errorf("Expected status 200, but got %v", w.Code)
	}
	if w.Body.Len() == 0 {
		t.Error("Expected body, but got none.")
	}
}
开发者ID:xperimental,项目名称:yovpn,代码行数:19,代码来源:web_test.go


示例18: TestCreate

func TestCreate(t *testing.T) {
	vars := url.Values{
		"resume_name": {"red dragon"},
	}
	req, err := http.NewRequest("POST", "/resume/create", strings.NewReader(vars.Encode()))
	if err != nil {
		t.Errorf("creating request %v", err)
	}
	req.Header.Set(echo.ContentType, echo.ApplicationForm)
	resp := httptest.NewRecorder()
	ctx := echo.NewContext(req, echo.NewResponse(resp), ts)
	ctx.Set("User", user)

	err = Create(ctx)
	if err != nil {
		t.Error(err)
	}
	if resp.Code != http.StatusFound {
		t.Errorf("expected  %d got %d", http.StatusFound, resp.Code)
	}
}
开发者ID:guus-vanweelden,项目名称:zedlist,代码行数:21,代码来源:resume_test.go


示例19: BenchmarkGzip

func BenchmarkGzip(b *testing.B) {

	b.StopTimer()
	b.ReportAllocs()

	h := func(c *echo.Context) error {
		c.Response().Write([]byte("test")) // For Content-Type sniffing
		return nil
	}
	req, _ := http.NewRequest(echo.GET, "/", nil)
	req.Header.Set(echo.AcceptEncoding, "gzip")

	b.StartTimer()

	for i := 0; i < b.N; i++ {
		rec := httptest.NewRecorder()
		c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
		Gzip()(h)(c)
	}

}
开发者ID:jameswei,项目名称:kingtask,代码行数:21,代码来源:compress_test.go


示例20: dummyContext

// Create dummy echo.Context with request for tests
// Note: echo makes it impossible to initialize the context response :(
func dummyContext() *echo.Context {
	req, _ := http.NewRequest("POST", "http://example.com", strings.NewReader("foo"))
	resp := &echo.Response{Writer: httptest.NewRecorder()}
	return echo.NewContext(req, resp, echo.New())
}
开发者ID:echo-contrib,项目名称:go_middleware,代码行数:7,代码来源:http_logger_test.go



注:本文中的github.com/labstack/echo.NewContext函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang echo.NewHTTPError函数代码示例发布时间:2022-05-23
下一篇:
Golang echo.New函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap