当前位置: 首页>>代码示例>>Golang>>正文


Golang http.NewRequest函数代码示例

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


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

示例1: TestOPTIONS

func TestOPTIONS(t *testing.T) {
	mux := NewTrieServeMux()
	mux.HandleFunc("GET", "/foo", func(w http.ResponseWriter, r *http.Request) {})
	mux.HandleFunc("POST", "/bar", func(w http.ResponseWriter, r *http.Request) {})
	w := &testResponseWriter{}
	r, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
	r.Header.Set(CORSRequestMethod, "GET")

	mux.ServeHTTP(w, r)
	if http.StatusOK != w.StatusCode {
		t.Fatal(w.StatusCode)
	}
	if "GET, HEAD, OPTIONS" != w.Header().Get("Allow") {
		t.Fatal(w.Header().Get("Allow"))
	}
	if "GET, HEAD, OPTIONS" != w.Header().Get(CORSAllowMethods) {
		t.Fatal(w.Header().Get("Allow"))
	}

	w = &testResponseWriter{}
	r, _ = http.NewRequest("OPTIONS", "http://example.com/bar", nil)
	mux.ServeHTTP(w, r)
	if http.StatusOK != w.StatusCode {
		t.Fatal(w.StatusCode)
	}
	if "OPTIONS, POST" != w.Header().Get("Allow") {
		t.Fatal(w.Header().Get("Allow"))
	}
}
开发者ID:nbrownus,项目名称:go-tigertonic,代码行数:29,代码来源:trie_serve_mux_test.go

示例2: TestRequestParsing

func (s *HTTPUtilSuite) TestRequestParsing(c *C) {
	req1, _ := http.NewRequest("GET", "http://127.0.0.1/hello", nil)
	req2, _ := http.NewRequest("GET", "http://domain.com/hello", nil)
	req3, _ := http.NewRequest("GET", "https://127.0.0.1:8080", nil)
	req4, _ := http.NewRequest("GET", "https://domain.com:8080", nil)
	req5, _ := http.NewRequest("GET", "", nil)

	c.Assert(req1, NotNil)
	c.Assert(req2, NotNil)
	c.Assert(req3, NotNil)
	c.Assert(req4, NotNil)
	c.Assert(req5, NotNil)

	c.Assert(GetRequestHost(req1), Equals, "127.0.0.1")
	c.Assert(GetRequestHost(req2), Equals, "domain.com")
	c.Assert(GetRequestHost(req3), Equals, "127.0.0.1")
	c.Assert(GetRequestHost(req4), Equals, "domain.com")
	c.Assert(GetRequestHost(req5), Equals, "")

	c.Assert(GetRequestPort(req1), Equals, "80")
	c.Assert(GetRequestPort(req2), Equals, "80")
	c.Assert(GetRequestPort(req3), Equals, "8080")
	c.Assert(GetRequestPort(req4), Equals, "8080")
	c.Assert(GetRequestPort(req5), Equals, "")
}
开发者ID:essentialkaos,项目名称:ek,代码行数:25,代码来源:httputil_test.go

示例3: Test_GenerateToken

func Test_GenerateToken(t *testing.T) {
	Convey("Generate token", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer())

		// Simulate login.
		m.Get("/login", func(sess session.Store, x CSRF) {
			sess.Set("uid", "123456")
		})

		// Generate token.
		m.Get("/private", func() {})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/login", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		cookie := resp.Header().Get("Set-Cookie")

		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)
	})
}
开发者ID:macaron-contrib,项目名称:csrf,代码行数:29,代码来源:csrf_test.go

示例4: execute

func (c *Client) execute(method, endpoint string, params map[string]string) ([]byte, error) {
	if c.HTTPClient == nil {
		c.HTTPClient = &http.Client{}
	}

	var (
		req        *http.Request
		requestErr error
	)

	if method != "GET" {
		req, requestErr = http.NewRequest(method, c.BaseURL+endpoint, bytes.NewBufferString(c.buildBody(params).Encode()))
		req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	} else {
		req, requestErr = http.NewRequest(method, c.buildURL(c.BaseURL, endpoint, params), nil)
	}
	if requestErr != nil {
		panic(requestErr)
	}

	req.Header.Add("X-ChatWorkToken", c.APIKey)

	resp, err := c.HTTPClient.Do(req)
	c.latestRateLimit = c.rateLimit(resp)

	if err != nil {
		return []byte(``), err
	}

	return c.parseBody(resp)
}
开发者ID:griffin-stewie,项目名称:go-chatwork,代码行数:31,代码来源:client.go

示例5: TestIfItWorks

func TestIfItWorks(t *testing.T) {
	t.Parallel()

	m := New()
	ch := make(chan string, 1)

	m.Get("/hello/:name", func(c C, w http.ResponseWriter, r *http.Request) {
		greeting := "Hello "
		if c.Env != nil {
			if g, ok := c.Env["greeting"]; ok {
				greeting = g.(string)
			}
		}
		ch <- greeting + c.URLParams["name"]
	})

	r, _ := http.NewRequest("GET", "/hello/carl", nil)
	m.ServeHTTP(httptest.NewRecorder(), r)
	out := <-ch
	if out != "Hello carl" {
		t.Errorf(`Unexpected response %q, expected "Hello carl"`, out)
	}

	r, _ = http.NewRequest("GET", "/hello/bob", nil)
	env := map[interface{}]interface{}{"greeting": "Yo "}
	m.ServeHTTPC(C{Env: env}, httptest.NewRecorder(), r)
	out = <-ch
	if out != "Yo bob" {
		t.Errorf(`Unexpected response %q, expected "Yo bob"`, out)
	}
}
开发者ID:FihlaTV,项目名称:bridge-server,代码行数:31,代码来源:mux_test.go

示例6: Test_LedisCacher

func Test_LedisCacher(t *testing.T) {
	Convey("Test ledis cache adapter", t, func() {
		opt := cache.Options{
			Adapter:       "ledis",
			AdapterConfig: "data_dir=./tmp.db",
			Interval:      1,
		}

		Convey("Basic operations", func() {
			t := tango.New()
			t.Use(cache.New(opt))

			t.Get("/", new(CacheAction))

			resp := httptest.NewRecorder()
			req, err := http.NewRequest("GET", "/", nil)
			So(err, ShouldBeNil)
			t.ServeHTTP(resp, req)

			t.Get("/id", new(Cache2Action))

			resp = httptest.NewRecorder()
			req, err = http.NewRequest("GET", "/id", nil)
			So(err, ShouldBeNil)
			t.ServeHTTP(resp, req)
		})
	})
}
开发者ID:tango-contrib,项目名称:cache-ledis,代码行数:28,代码来源:ledis_test.go

示例7: TestFilterParam

// TestFilterParam tests the ability to apply middleware
// function to filter all routes with specified parameter
// in the REST url
func TestFilterParam(t *testing.T) {

	r, _ := http.NewRequest("GET", "/:id", nil)
	w := httptest.NewRecorder()

	// first test that the param filter does not trigger
	handler := new(RouteMux)
	handler.Get("/", HandlerOk)
	handler.Get("/:id", HandlerOk)
	handler.FilterParam("id", FilterId)
	handler.ServeHTTP(w, r)

	if w.Code != http.StatusOK {
		t.Errorf("Code set to [%v]; want [%v]", w.Code, http.StatusOK)
	}

	// now test the param filter does trigger
	r, _ = http.NewRequest("GET", "/admin", nil)
	w = httptest.NewRecorder()
	handler.ServeHTTP(w, r)

	if w.Code != http.StatusUnauthorized {
		t.Errorf("Did not apply Param Filter. Code set to [%v]; want [%v]", w.Code, http.StatusUnauthorized)
	}

}
开发者ID:rlizana,项目名称:routes,代码行数:29,代码来源:routes_test.go

示例8: Test_GenerateCustomHeader

func Test_GenerateCustomHeader(t *testing.T) {
	m := martini.Classic()
	store := sessions.NewCookieStore([]byte("secret123"))
	m.Use(sessions.Sessions("my_session", store))
	m.Use(Generate(&Options{
		Secret:     "token123",
		SessionKey: "userID",
		SetHeader:  true,
		Header:     "X-SEESurfToken",
	}))

	// Simulate login.
	m.Get("/login", func(s sessions.Session) string {
		s.Set("userID", "123456")
		return "OK"
	})

	// Generate HTTP header.
	m.Get("/private", func(s sessions.Session, x CSRF) string {
		return "OK"
	})

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/login", nil)
	m.ServeHTTP(res, req)

	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/private", nil)
	req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
	m.ServeHTTP(res2, req2)

	if res2.Header().Get("X-SEESurfToken") == "" {
		t.Error("Failed to set X-SEESurfToken custom header")
	}
}
开发者ID:rverton,项目名称:csrf,代码行数:35,代码来源:csrf_test.go

示例9: Test_Validate

func Test_Validate(t *testing.T) {
	m := martini.Classic()
	store := sessions.NewCookieStore([]byte("secret123"))
	m.Use(sessions.Sessions("my_session", store))
	m.Use(Generate(&Options{
		Secret:     "token123",
		SessionKey: "userID",
	}))

	// Simulate login.
	m.Get("/login", func(s sessions.Session) string {
		s.Set("userID", "123456")
		return "OK"
	})

	// Generate token.
	m.Get("/private", func(s sessions.Session, x CSRF) string {
		return x.GetToken()
	})

	m.Post("/private", Validate, func(s sessions.Session) string {
		return "OK"
	})

	// Login to set session.
	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/login", nil)
	m.ServeHTTP(res, req)

	cookie := res.Header().Get("Set-Cookie")

	// Get a new token.
	res2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/private", nil)
	req2.Header.Set("Cookie", cookie)
	m.ServeHTTP(res2, req2)

	// Post using _csrf form value.
	data := url.Values{}
	data.Set("_csrf", res2.Body.String())
	res3 := httptest.NewRecorder()
	req3, _ := http.NewRequest("POST", "/private", bytes.NewBufferString(data.Encode()))
	req3.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req3.Header.Set("Content-Length", strconv.Itoa(len(data.Encode())))
	req3.Header.Set("Cookie", cookie)
	m.ServeHTTP(res3, req3)
	if res3.Code == 400 {
		t.Error("Validation of _csrf form value failed")
	}

	// Post using X-CSRFToken HTTP header.
	res4 := httptest.NewRecorder()
	req4, _ := http.NewRequest("POST", "/private", nil)
	req4.Header.Set("X-CSRFToken", res2.Body.String())
	req4.Header.Set("Cookie", cookie)
	m.ServeHTTP(res4, req4)
	if res4.Code == 400 {
		t.Error("Validation of X-CSRFToken failed")
	}
}
开发者ID:rverton,项目名称:csrf,代码行数:60,代码来源:csrf_test.go

示例10: TestReceivesDelete

func TestReceivesDelete(t *testing.T) {
	dc := testdataclient.New([]*eskip.Route{
		{Id: "route1", Path: "/some-path", Backend: "https://www.example.org"},
		{Id: "route2", Path: "/some-other", Backend: "https://other.example.org"}})
	rt := routing.New(routing.Options{
		UpdateBuffer: 0,
		DataClients:  []routing.DataClient{dc},
		PollTimeout:  pollTimeout})

	req, err := http.NewRequest("GET", "https://www.example.com/some-path", nil)
	if err != nil {
		t.Error(err)
	}

	<-waitRoute(rt, req)
	<-waitUpdate(dc, nil, []string{"route1"}, false)
	time.Sleep(6 * pollTimeout)

	req, err = http.NewRequest("GET", "https://www.example.com/some-path", nil)
	if err != nil {
		t.Error(err)
	}

	if waitDone(0, waitRoute(rt, req)) {
		t.Error("should not have found route")
	}
}
开发者ID:nishanthvasudevan,项目名称:skipper,代码行数:27,代码来源:routing_test.go

示例11: TestMergesMultipleSources

func TestMergesMultipleSources(t *testing.T) {
	if testing.Short() {
		t.Skip()
	}

	dc1 := testdataclient.New([]*eskip.Route{{Id: "route1", Path: "/some-path", Backend: "https://www.example.org"}})
	dc2 := testdataclient.New([]*eskip.Route{{Id: "route2", Path: "/some-other", Backend: "https://other.example.org"}})
	dc3 := testdataclient.New([]*eskip.Route{{Id: "route3", Path: "/another", Backend: "https://another.example.org"}})
	rt := routing.New(routing.Options{
		UpdateBuffer: 0,
		DataClients:  []routing.DataClient{dc1, dc2, dc3},
		PollTimeout:  pollTimeout})

	req1, err := http.NewRequest("GET", "https://www.example.com/some-path", nil)
	if err != nil {
		t.Error(err)
	}

	req2, err := http.NewRequest("GET", "https://www.example.com/some-other", nil)
	if err != nil {
		t.Error(err)
	}

	req3, err := http.NewRequest("GET", "https://www.example.com/another", nil)
	if err != nil {
		t.Error(err)
	}

	if !waitDone(6*pollTimeout,
		waitRoute(rt, req1),
		waitRoute(rt, req2),
		waitRoute(rt, req3)) {
		t.Error("test timeout")
	}
}
开发者ID:nishanthvasudevan,项目名称:skipper,代码行数:35,代码来源:routing_test.go

示例12: TestKeepContext

// Tests that the context is cleared or not cleared properly depending on
// the configuration of the router
func TestKeepContext(t *testing.T) {
	func1 := func(w http.ResponseWriter, r *http.Request) {}

	r := NewRouter()
	r.HandleFunc("/", func1).Name("func1")

	req, _ := http.NewRequest("GET", "http://localhost/", nil)
	context.Set(req, "t", 1)

	res := new(http.ResponseWriter)
	r.ServeHTTP(*res, req)

	if _, ok := context.GetOk(req, "t"); ok {
		t.Error("Context should have been cleared at end of request")
	}

	r.KeepContext = true

	req, _ = http.NewRequest("GET", "http://localhost/", nil)
	context.Set(req, "t", 1)

	r.ServeHTTP(*res, req)
	if _, ok := context.GetOk(req, "t"); !ok {
		t.Error("Context should NOT have been cleared at end of request")
	}

}
开发者ID:jboelter,项目名称:mux,代码行数:29,代码来源:mux_test.go

示例13: TestGzip

func TestGzip(t *testing.T) {
	// Empty Accept-Encoding header
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	h := func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	Gzip()(h)(c)
	assert.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, "test", rec.Body.String())

	// With Accept-Encoding header
	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()(h)(c)
	assert.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, "gzip", rec.Header().Get(echo.ContentEncoding))
	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:orktes,项目名称:captainhub,代码行数:28,代码来源:compress_test.go

示例14: createAzureRequest

// createAzureRequest packages up the request with the correct set of headers and returns
// the request object or an error.
func (client client) createAzureRequest(url string, requestType string, contentType string, data []byte) (*http.Request, error) {
	var request *http.Request
	var err error

	if data != nil {
		body := bytes.NewBuffer(data)
		request, err = http.NewRequest(requestType, url, body)
	} else {
		request, err = http.NewRequest(requestType, url, nil)
	}

	if err != nil {
		return nil, err
	}

	request.Header.Set(msVersionHeader, client.config.APIVersion)
	request.Header.Set(uaHeader, client.config.UserAgent)

	if contentType != "" {
		request.Header.Set(contentHeader, contentType)
	} else {
		request.Header.Set(contentHeader, defaultContentHeaderValue)
	}

	return request, nil
}
开发者ID:paultyng,项目名称:terraform,代码行数:28,代码来源:http.go

示例15: resourceSetup

// Returns a routeset with N *resources per namespace*. so N=1 gives about 15 routes
func resourceSetup(N int) (namespaces []string, resources []string, requests []*http.Request) {
	namespaces = []string{"admin", "api", "site"}
	resources = []string{}

	for i := 0; i < N; i++ {
		sha1 := sha1.New()
		io.WriteString(sha1, fmt.Sprintf("%d", i))
		strResource := fmt.Sprintf("%x", sha1.Sum(nil))
		resources = append(resources, strResource)
	}

	for _, ns := range namespaces {
		for _, res := range resources {
			req, _ := http.NewRequest("GET", "/"+ns+"/"+res, nil)
			requests = append(requests, req)
			req, _ = http.NewRequest("POST", "/"+ns+"/"+res, nil)
			requests = append(requests, req)
			req, _ = http.NewRequest("GET", "/"+ns+"/"+res+"/3937", nil)
			requests = append(requests, req)
			req, _ = http.NewRequest("PUT", "/"+ns+"/"+res+"/3937", nil)
			requests = append(requests, req)
			req, _ = http.NewRequest("DELETE", "/"+ns+"/"+res+"/3937", nil)
			requests = append(requests, req)
		}
	}

	return
}
开发者ID:ae6rt,项目名称:goref,代码行数:29,代码来源:speed_test.go


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