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

Golang test.MakeSimpleRequest函数代码示例

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

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



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

示例1: TestJSONP

func TestJSONP(t *testing.T) {

	handler := ResourceHandler{
		DisableJsonIndent: true,
		PreRoutingMiddlewares: []Middleware{
			&JsonpMiddleware{},
		},
	}
	handler.SetRoutes(
		&Route{"GET", "/ok",
			func(w ResponseWriter, r *Request) {
				w.WriteJson(map[string]string{"Id": "123"})
			},
		},
		&Route{"GET", "/error",
			func(w ResponseWriter, r *Request) {
				Error(w, "gzipped error", 500)
			},
		},
	)

	recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/ok?callback=parseResponse", nil))
	recorded.CodeIs(200)
	recorded.HeaderIs("Content-Type", "text/javascript")
	recorded.BodyIs("parseResponse({\"Id\":\"123\"})")

	recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/error?callback=parseResponse", nil))
	recorded.CodeIs(500)
	recorded.HeaderIs("Content-Type", "text/javascript")
	recorded.BodyIs("parseResponse({\"Error\":\"gzipped error\"})")
}
开发者ID:auroralaboratories,项目名称:corona-api,代码行数:31,代码来源:jsonp_test.go


示例2: TestContentTypeCheckerMiddleware

func TestContentTypeCheckerMiddleware(t *testing.T) {

	api := NewApi()

	// the middleware to test
	api.Use(&ContentTypeCheckerMiddleware{})

	// a simple app
	api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
		w.WriteJson(map[string]string{"Id": "123"})
	}))

	// wrap all
	handler := api.MakeHandler()

	// no payload, no content length, no check
	recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/", nil))
	recorded.CodeIs(200)

	// JSON payload with correct content type
	recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("POST", "http://localhost/", map[string]string{"Id": "123"}))
	recorded.CodeIs(200)

	// JSON payload with correct content type specifying the utf-8 charset
	req := test.MakeSimpleRequest("POST", "http://localhost/", map[string]string{"Id": "123"})
	req.Header.Set("Content-Type", "application/json; charset=utf-8")
	recorded = test.RunRequest(t, handler, req)
	recorded.CodeIs(200)

	// JSON payload with incorrect content type
	req = test.MakeSimpleRequest("POST", "http://localhost/", map[string]string{"Id": "123"})
	req.Header.Set("Content-Type", "text/x-json")
	recorded = test.RunRequest(t, handler, req)
	recorded.CodeIs(415)
}
开发者ID:charshy,项目名称:registry,代码行数:35,代码来源:content_type_checker_test.go


示例3: TestHandler

func TestHandler(t *testing.T) {

	handler := rest.ResourceHandler{
		DisableJsonIndent: true,
		ErrorLogger:       log.New(ioutil.Discard, "", 0),
	}

	handler.SetRoutes(
		&rest.Route{"POST", "/api/coach/checkin",
			func(w rest.ResponseWriter, r *rest.Request) {
				w.WriteHeader(http.StatusCreated)
				data := map[string]string{"id": "53f87e7ad18a68e0a884d31e"}
				w.WriteJson(data)
			},
		},
		&rest.Route{"POST", "/api/coach/checkout",
			func(w rest.ResponseWriter, r *rest.Request) {
				w.WriteHeader(http.StatusAccepted)
			},
		},
	)

	recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest(
		"POST", "http://www.sprint3r.com/api/coach/checkin", &map[string]string{"name": "iporsut", "league": "dtac"}))
	recorded.CodeIs(201)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"id":"53f87e7ad18a68e0a884d31e"}`)

	recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest(
		"POST", "http://www.sprint3r.com/api/coach/checkout", &map[string]string{"name": "iporsut", "league": "dtac"}))
	recorded.CodeIs(202)
	recorded.ContentTypeIsJson()
}
开发者ID:roongr2k7,项目名称:time_tracker_api,代码行数:33,代码来源:handler_test.go


示例4: TestJsonpMiddleware

func TestJsonpMiddleware(t *testing.T) {

	api := NewApi()

	// the middleware to test
	api.Use(&JsonpMiddleware{})

	// router app with success and error paths
	router, err := MakeRouter(
		Get("/ok", func(w ResponseWriter, r *Request) {
			w.WriteJson(map[string]string{"Id": "123"})
		}),
		Get("/error", func(w ResponseWriter, r *Request) {
			Error(w, "jsonp error", 500)
		}),
	)
	if err != nil {
		t.Fatal(err)
	}

	api.SetApp(router)

	// wrap all
	handler := api.MakeHandler()

	recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/ok?callback=parseResponse", nil))
	recorded.CodeIs(200)
	recorded.HeaderIs("Content-Type", "text/javascript")
	recorded.BodyIs("parseResponse({\"Id\":\"123\"})")

	recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/error?callback=parseResponse", nil))
	recorded.CodeIs(500)
	recorded.HeaderIs("Content-Type", "text/javascript")
	recorded.BodyIs("parseResponse({\"Error\":\"jsonp error\"})")
}
开发者ID:freeformz,项目名称:go-inkblot,代码行数:35,代码来源:jsonp_test.go


示例5: TestGzipEnabled

func TestGzipEnabled(t *testing.T) {

	handler := ResourceHandler{
		DisableJsonIndent: true,
		EnableGzip:        true,
	}
	handler.SetRoutes(
		&Route{"GET", "/ok",
			func(w ResponseWriter, r *Request) {
				w.WriteJson(map[string]string{"Id": "123"})
			},
		},
		&Route{"GET", "/error",
			func(w ResponseWriter, r *Request) {
				Error(w, "gzipped error", 500)
			},
		},
	)

	recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/ok", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()
	recorded.ContentEncodingIsGzip()
	recorded.HeaderIs("Vary", "Accept-Encoding")

	recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/error", nil))
	recorded.CodeIs(500)
	recorded.ContentTypeIsJson()
	recorded.ContentEncodingIsGzip()
	recorded.HeaderIs("Vary", "Accept-Encoding")
}
开发者ID:auroralaboratories,项目名称:corona-api,代码行数:31,代码来源:gzip_test.go


示例6: TestAccessLogApacheMiddlewareMissingData

func TestAccessLogApacheMiddlewareMissingData(t *testing.T) {

	api := NewApi()

	// the uncomplete middlewares stack
	buffer := bytes.NewBufferString("")
	api.Use(&AccessLogApacheMiddleware{
		Logger:       log.New(buffer, "", 0),
		Format:       CommonLogFormat,
		textTemplate: nil,
	})

	// a simple app
	api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
		w.WriteJson(map[string]string{"Id": "123"})
	}))

	// wrap all
	handler := api.MakeHandler()

	req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
	recorded := test.RunRequest(t, handler, req)
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()

	// not much to log when the Env data is missing, but this should still work
	apacheCommon := regexp.MustCompile(` - -  "GET / HTTP/1.1" 0 -`)

	if !apacheCommon.Match(buffer.Bytes()) {
		t.Errorf("Got: %s", buffer.String())
	}
}
开发者ID:Catroque,项目名称:go-json-rest,代码行数:32,代码来源:access_log_apache_test.go


示例7: TestAccessLogApacheMiddleware

func TestAccessLogApacheMiddleware(t *testing.T) {

	api := NewApi()

	// the middlewares stack
	buffer := bytes.NewBufferString("")
	api.Use(&AccessLogApacheMiddleware{
		Logger:       log.New(buffer, "", 0),
		Format:       CommonLogFormat,
		textTemplate: nil,
	})
	api.Use(&TimerMiddleware{})
	api.Use(&RecorderMiddleware{})

	// a simple app
	api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
		w.WriteJson(map[string]string{"Id": "123"})
	}))

	// wrap all
	handler := api.MakeHandler()

	req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
	req.RemoteAddr = "127.0.0.1:1234"
	recorded := test.RunRequest(t, handler, req)
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()

	// log tests, eg: '127.0.0.1 - - 29/Nov/2014:22:28:34 +0000 "GET / HTTP/1.1" 200 12'
	apacheCommon := regexp.MustCompile(`127.0.0.1 - - \d{2}/\w{3}/\d{4}:\d{2}:\d{2}:\d{2} [+\-]\d{4}\ "GET / HTTP/1.1" 200 12`)

	if !apacheCommon.Match(buffer.Bytes()) {
		t.Errorf("Got: %s", buffer.String())
	}
}
开发者ID:Catroque,项目名称:go-json-rest,代码行数:35,代码来源:access_log_apache_test.go


示例8: APIRequest

func APIRequest(url string, method string, model interface{}, token string) {
	jwtMiddleware := &jwt.JWTMiddleware{
		Key:        SecretKey,
		Realm:      Realm,
		Timeout:    time.Hour,
		MaxRefresh: time.Hour * 24,
		Authenticator: func(userId string, password string) bool {
			return Authenticator(userId, password)
		},
	}

	api := rest.NewApi()
	api.Use(&rest.IfMiddleware{
		Condition: func(request *rest.Request) bool {
			return CheckCondition(request)
		},
		IfTrue: jwtMiddleware,
	})

	api.SetApp(NewRouter(jwtMiddleware, testConn))

	Request = test.MakeSimpleRequest(method, url, model)
	if token != "" {
		Request.Header.Set("Authorization", "Bearer "+token)
	}
	recorded := test.RunRequest(tst, api.MakeHandler(), Request)
	Response = recorded.Recorder
}
开发者ID:yetis-br,项目名称:travelPlanning,代码行数:28,代码来源:travelPlanning_suite_test.go


示例9: TestGetChannels

func TestGetChannels(t *testing.T) {
	handler, err := MakeHandler()
	assert.NoError(t, err)
	recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/channels", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()
}
开发者ID:joshheinrichs,项目名称:geosource,代码行数:7,代码来源:channels_test.go


示例10: TestGetEmailVerify

func TestGetEmailVerify(t *testing.T) {
	handler := newHandler()

	type testpair struct {
		email string
		valid bool
	}

	var tests = []testpair{
		{"[email protected]", true},
		{"[email protected]", true},
		{"[email protected]", false},
		{"not%20an%20email", false},
	}

	for _, pair := range tests {
		recorded := test.RunRequest(t, &handler,
			test.MakeSimpleRequest("GET",
				"http://1.2.3.4/verify/?email="+pair.email, nil))
		recorded.CodeIs(200)
		recorded.ContentTypeIsJson()

		// check actual response content
		msg := Message{}
		recorded.DecodeJsonPayload(&msg)
		if msg.IsValid != pair.valid {
			t.Errorf("For %v. Expected %v: Actual %v", pair.email, pair.valid, msg.IsValid)
		}
	}
}
开发者ID:taterbase,项目名称:smtp-callback-verification,代码行数:30,代码来源:web_test.go


示例11: TestAccountHandlerGetAllRefresh

func TestAccountHandlerGetAllRefresh(t *testing.T) {
	ctx, handler := NewTestHandler(t)
	defer ctx.Close()

	c := core.NewTestConfig(t)
	var ff gateway.FeedFactory = &gateway.AccountFeedFactory{AccountRefresh: c.AccountRefresh}
	WaitForFeed(t, ctx, &ff, 15*time.Second)

	nc := make(chan *core.Notification)
	ctx.N.Subscribe(nc)
	defer ctx.N.Unsubscribe(nc)

	go func() {
		req := test.MakeSimpleRequest("GET", "http://1.2.3.4/v1/accounts", nil)
		req.Header.Add("Cache-Control", "private; max-age=0")
		test.RunRequest(t, handler, req)
		// NB: This request will not return data, as there's no feed running.
		// Long timeouts avoided as the ctx.Close() closes the Notifier,
		// which in turn closes the RefreshIfNeeded listener.
	}()

outer:
	for {
		select {
		case msg := <-nc:
			if msg.Type == core.NtAccountRefresh {
				// controller requested an account refresh, like it should have
				break outer
			}
		case <-time.After(15 * time.Second):
			t.Fatal("controller didn't request update before timeout")
		}
	}
}
开发者ID:jacktang,项目名称:ibconnect.go,代码行数:34,代码来源:account_handler_test.go


示例12: TestCall

func TestCall(t *testing.T) {
	err := os.Chdir("../../")
	if err != nil {
		log.Fatal(err)
	}

	handler := MakeHandler()

	// Use BackendToken to avoid login
	err = variables.LoadTokenKeys()
	if err != nil {
		t.Fatal(err)
	}
	// Test that call works
	path := variables.APIPathCallServer
	path = strings.Replace(path, ":number", "test number", 1)
	testReq := test.MakeSimpleRequest(
		"GET",
		"http://localhost"+path,
		nil,
	)
	testReq.Header.Set("Authorization", "Bearer "+variables.BackendToken)
	// Do not gzip the response
	testReq.Header.Set("Accept-Encoding", "identity")
	testRes := test.RunRequest(t, *handler, testReq)
	testRes.CodeIs(http.StatusOK)
	testRes.ContentTypeIsJson()
}
开发者ID:pdxjohnny,项目名称:hangouts-call-center,代码行数:28,代码来源:call_test.go


示例13: TestRecoverMiddleware

func TestRecoverMiddleware(t *testing.T) {

	api := NewApi()

	// the middleware to test
	api.Use(&RecoverMiddleware{
		Logger:                   log.New(ioutil.Discard, "", 0),
		EnableLogAsJson:          false,
		EnableResponseStackTrace: true,
	})

	// a simple app that fails
	api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
		panic("test")
	}))

	// wrap all
	handler := api.MakeHandler()

	req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
	recorded := test.RunRequest(t, handler, req)
	recorded.CodeIs(500)
	recorded.ContentTypeIsJson()

	// payload
	payload := map[string]string{}
	err := recorded.DecodeJsonPayload(&payload)
	if err != nil {
		t.Fatal(err)
	}
	if payload["error"] == "" {
		t.Errorf("Expected an error message, got: %v", payload)
	}
}
开发者ID:mhemmings,项目名称:go-json-rest,代码行数:34,代码来源:recover_test.go


示例14: TestGJRMiddleware

// TestRate tests ratelimit.Rate methods.
func TestGJRMiddleware(t *testing.T) {
	api := rest.NewApi()

	api.Use(NewGJRMiddleware(newRedisLimiter("10-M", "limitertests:gjr")))

	var reset int64

	api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
		reset = r.Env["ratelimit:reset"].(int64)
		w.WriteJson(map[string]string{"message": "ok"})
	}))

	handler := api.MakeHandler()
	req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
	req.RemoteAddr = fmt.Sprintf("178.1.2.%d:120", Random(1, 90))

	i := 1
	for i < 20 {
		recorded := test.RunRequest(t, handler, req)
		assert.True(t, math.Ceil(time.Since(time.Unix(reset, 0)).Seconds()) <= 60)
		if i <= 10 {
			recorded.BodyIs(`{"message":"ok"}`)
			recorded.HeaderIs("X-Ratelimit-Limit", "10")
			recorded.HeaderIs("X-Ratelimit-Remaining", fmt.Sprintf("%d", 10-i))
			recorded.CodeIs(200)
		} else {
			recorded.BodyIs(`{"Error":"Limit exceeded"}`)
			recorded.HeaderIs("X-Ratelimit-Limit", "10")
			recorded.HeaderIs("X-Ratelimit-Remaining", "0")
			recorded.CodeIs(429)
		}
		i++
	}
}
开发者ID:wppurking,项目名称:limiter,代码行数:35,代码来源:middleware_gjr_test.go


示例15: TestGJRMiddlewareWithRaceCondition

// TestGJRMiddlewareWithRaceCondition test GRJ middleware under race condition.
func TestGJRMiddlewareWithRaceCondition(t *testing.T) {
	runtime.GOMAXPROCS(4)

	api := rest.NewApi()

	api.Use(NewGJRMiddleware(newRedisLimiter("5-M", "limitertests:gjrrace")))

	api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
		w.WriteJson(map[string]string{"message": "ok"})
	}))

	handler := api.MakeHandler()
	req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
	req.RemoteAddr = fmt.Sprintf("178.1.2.%d:180", Random(1, 90))

	nbRequests := 100
	successCount := 0

	var wg sync.WaitGroup
	wg.Add(nbRequests)

	for i := 1; i <= nbRequests; i++ {
		go func() {
			recorded := test.RunRequest(t, handler, req)
			if recorded.Recorder.Code == 200 {
				successCount++
			}
			wg.Done()
		}()
	}

	wg.Wait()

	assert.Equal(t, 5, successCount)
}
开发者ID:wppurking,项目名称:limiter,代码行数:36,代码来源:middleware_gjr_test.go


示例16: TestStatus

func TestStatus(t *testing.T) {

	handler := ResourceHandler{
		EnableStatusService: true,
	}
	handler.SetRoutes(
		&Route{"GET", "/r",
			func(w ResponseWriter, r *Request) {
				w.WriteJson(map[string]string{"Id": "123"})
			},
		},
		&Route{"GET", "/.status",
			func(w ResponseWriter, r *Request) {
				w.WriteJson(handler.GetStatus())
			},
		},
	)

	// one request to the API
	recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/r", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()

	// check the status
	recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/.status", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()

	payload := map[string]interface{}{}

	err := recorded.DecodeJsonPayload(&payload)
	if err != nil {
		t.Fatal(err)
	}

	if payload["Pid"] == nil {
		t.Error("Expected a non nil Pid")
	}

	if payload["TotalCount"].(float64) != 1 {
		t.Errorf("TotalCount 1 Expected, got: %f", payload["TotalCount"].(float64))
	}

	if payload["StatusCodeCount"].(map[string]interface{})["200"].(float64) != 1 {
		t.Errorf("StatusCodeCount 200 1 Expected, got: %f", payload["StatusCodeCount"].(map[string]interface{})["200"].(float64))
	}
}
开发者ID:auroralaboratories,项目名称:corona-api,代码行数:47,代码来源:status_test.go


示例17: TestStatusMiddleware

func TestStatusMiddleware(t *testing.T) {

	api := NewApi()

	// the middlewares
	status := &StatusMiddleware{}
	api.Use(status)
	api.Use(&TimerMiddleware{})
	api.Use(&RecorderMiddleware{})

	// an app that return the Status
	api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
		w.WriteJson(status.GetStatus())
	}))

	// wrap all
	handler := api.MakeHandler()

	// one request
	recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/1", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()

	// another request
	recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/2", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()

	// payload
	payload := map[string]interface{}{}
	err := recorded.DecodeJsonPayload(&payload)
	if err != nil {
		t.Fatal(err)
	}

	if payload["Pid"] == nil {
		t.Error("Expected a non nil Pid")
	}

	if payload["TotalCount"].(float64) != 1 {
		t.Errorf("TotalCount 1 Expected, got: %f", payload["TotalCount"].(float64))
	}

	if payload["StatusCodeCount"].(map[string]interface{})["200"].(float64) != 1 {
		t.Errorf("StatusCodeCount 200 1 Expected, got: %f", payload["StatusCodeCount"].(map[string]interface{})["200"].(float64))
	}
}
开发者ID:Catroque,项目名称:go-json-rest,代码行数:47,代码来源:status_test.go


示例18: TestAllOtherPathsNeedAuth

func TestAllOtherPathsNeedAuth(t *testing.T) {
	handler := MakeHandler()

	req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
	res := test.RunRequest(t, *handler, req)
	res.CodeIs(401)
	res.ContentTypeIsJson()
}
开发者ID:pdxjohnny,项目名称:numapp,代码行数:8,代码来源:auth_test.go


示例19: TestAuthBasic

func TestAuthBasic(t *testing.T) {

	handler := ResourceHandler{
		PreRoutingMiddlewares: []Middleware{
			&AuthBasicMiddleware{
				Realm: "test zone",
				Authenticator: func(userId string, password string) bool {
					if userId == "admin" && password == "admin" {
						return true
					}
					return false
				},
			},
		},
	}
	handler.SetRoutes(
		&Route{"GET", "/r",
			func(w ResponseWriter, r *Request) {
				w.WriteJson(map[string]string{"Id": "123"})
			},
		},
	)

	// simple request fails
	recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/r", nil))
	recorded.CodeIs(401)
	recorded.ContentTypeIsJson()

	// auth with wrong cred fails
	wrongCredReq := test.MakeSimpleRequest("GET", "http://1.2.3.4/r", nil)
	encoded := base64.StdEncoding.EncodeToString([]byte("admin:AdmIn"))
	wrongCredReq.Header.Set("Authorization", "Basic "+encoded)
	recorded = test.RunRequest(t, &handler, wrongCredReq)
	recorded.CodeIs(401)
	recorded.ContentTypeIsJson()

	// auth with right cred succeeds
	rightCredReq := test.MakeSimpleRequest("GET", "http://1.2.3.4/r", nil)
	encoded = base64.StdEncoding.EncodeToString([]byte("admin:admin"))
	rightCredReq.Header.Set("Authorization", "Basic "+encoded)
	recorded = test.RunRequest(t, &handler, rightCredReq)
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()
}
开发者ID:auroralaboratories,项目名称:corona-api,代码行数:44,代码来源:auth_basic_test.go


示例20: TestIfMiddleware

func TestIfMiddleware(t *testing.T) {

	api := NewApi()

	// the middleware to test
	api.Use(&IfMiddleware{
		Condition: func(r *Request) bool {
			if r.URL.Path == "/true" {
				return true
			}
			return false
		},
		IfTrue: MiddlewareSimple(func(handler HandlerFunc) HandlerFunc {
			return func(w ResponseWriter, r *Request) {
				r.Env["TRUE_MIDDLEWARE"] = true
				handler(w, r)
			}
		}),
		IfFalse: MiddlewareSimple(func(handler HandlerFunc) HandlerFunc {
			return func(w ResponseWriter, r *Request) {
				r.Env["FALSE_MIDDLEWARE"] = true
				handler(w, r)
			}
		}),
	})

	// a simple app
	api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
		w.WriteJson(r.Env)
	}))

	// wrap all
	handler := api.MakeHandler()

	recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()
	recorded.BodyIs("{\"FALSE_MIDDLEWARE\":true}")

	recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/true", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()
	recorded.BodyIs("{\"TRUE_MIDDLEWARE\":true}")
}
开发者ID:Catroque,项目名称:go-json-rest,代码行数:44,代码来源:if_test.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang test.RunRequest函数代码示例发布时间:2022-05-24
下一篇:
Golang rest.ResponseWriter类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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