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")) } }
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, "") }
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) }) }
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) }
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) } }
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) }) }) }
// 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) } }
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") } }
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") } }
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") } }
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") } }
// 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") } }
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()) } }
// 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 }
// 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 }
func Test_GenerateCustomCookie(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", SetCookie: true, Cookie: "seesurf", })) // Simulate login. m.Get("/login", func(s sessions.Session) string { s.Set("userID", "123456") return "OK" }) // Generate cookie. 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 !strings.Contains(res2.Header().Get("Set-Cookie"), "seesurf") { t.Error("Failed to set custom csrf cookie") } }
func (s *S) TestAddPool(c *check.C) { b := bytes.NewBufferString("name=pool1") req, err := http.NewRequest("POST", "/pools", b) c.Assert(err, check.IsNil) req.Header.Set("Authorization", "bearer "+s.token.GetValue()) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") rec := httptest.NewRecorder() defer provision.RemovePool("pool1") m := RunServer(true) m.ServeHTTP(rec, req) c.Assert(rec.Code, check.Equals, http.StatusCreated) c.Assert(err, check.IsNil) pools, err := provision.ListPools(bson.M{"_id": "pool1"}) c.Assert(err, check.IsNil) c.Assert(pools, check.HasLen, 1) b = bytes.NewBufferString("name=pool2&public=true") req, err = http.NewRequest("POST", "/pools", b) c.Assert(err, check.IsNil) req.Header.Set("Authorization", "bearer "+s.token.GetValue()) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") rec = httptest.NewRecorder() defer provision.RemovePool("pool2") m.ServeHTTP(rec, req) c.Assert(rec.Code, check.Equals, http.StatusCreated) pools, err = provision.ListPools(bson.M{"_id": "pool2"}) c.Assert(err, check.IsNil) c.Assert(pools[0].Public, check.Equals, true) }
func Test_LogoutOnAccessTokenExpiration(t *testing.T) { recorder := httptest.NewRecorder() s := sessions.NewCookieStore([]byte("secret123")) m := martini.Classic() m.Use(sessions.Sessions("my_session", s)) m.Use(Google( &oauth2.Config{ ClientID: "client_id", ClientSecret: "client_secret", RedirectURL: "redirect_url", }, )) m.Get("/addtoken", func(s sessions.Session) { s.Set(keyToken, "dummy token") }) m.Get("/", func(s sessions.Session) { if s.Get(keyToken) != nil { t.Errorf("User not logged out although access token is expired.") } }) addtoken, _ := http.NewRequest("GET", "/addtoken", nil) index, _ := http.NewRequest("GET", "/", nil) m.ServeHTTP(recorder, addtoken) m.ServeHTTP(recorder, index) }
func TestSnapshot_BadMethods(t *testing.T) { httpTest(t, func(srv *HTTPServer) { body := bytes.NewBuffer(nil) req, err := http.NewRequest("POST", "/v1/snapshot", body) if err != nil { t.Fatalf("err: %v", err) } resp := httptest.NewRecorder() _, err = srv.Snapshot(resp, req) if err != nil { t.Fatalf("err: %v", err) } if resp.Code != 405 { t.Fatalf("bad code: %d", resp.Code) } }) httpTest(t, func(srv *HTTPServer) { body := bytes.NewBuffer(nil) req, err := http.NewRequest("DELETE", "/v1/snapshot", body) if err != nil { t.Fatalf("err: %v", err) } resp := httptest.NewRecorder() _, err = srv.Snapshot(resp, req) if err != nil { t.Fatalf("err: %v", err) } if resp.Code != 405 { t.Fatalf("bad code: %d", resp.Code) } }) }
func Test_Logout(t *testing.T) { recorder := httptest.NewRecorder() s := sessions.NewCookieStore([]byte("secret123")) m := martini.Classic() m.Use(sessions.Sessions("my_session", s)) m.Use(Google( &oauth2.Config{ ClientID: "client_id", ClientSecret: "client_secret", RedirectURL: "redirect_url", }, )) m.Get("/", func(s sessions.Session) { s.Set(keyToken, "dummy token") }) m.Get("/get", func(s sessions.Session) { if s.Get(keyToken) != nil { t.Errorf("User credentials are still kept in the session.") } }) logout, _ := http.NewRequest("GET", "/logout", nil) index, _ := http.NewRequest("GET", "/", nil) m.ServeHTTP(httptest.NewRecorder(), index) m.ServeHTTP(recorder, logout) if recorder.Code != 302 { t.Errorf("Not being redirected to the next page.") } }
// Ensure that version validation middleware passes through request // on a valid version, and returns a 400 on an invalid version. func TestVersionMiddleware(t *testing.T) { assert := assert.New(t) api := NewAPI(&Configuration{}) handler := new(MockResourceHandler) handler.On("Authenticate").Return(nil) handler.On("ValidVersions").Return([]string{"1"}) handler.On("Rules").Return(&rules{}) handler.On("ResourceName").Return("widgets") handler.On("ReadResourceList").Return([]Resource{"foo"}, "", nil) api.RegisterResourceHandler(handler) // Valid version req, _ := http.NewRequest("GET", "http://example.com/api/v1/widgets", nil) w := httptest.NewRecorder() api.ServeHTTP(w, req) assert.Equal(w.Code, 200) assert.Contains(w.Body.String(), "foo") // Invalid version req, _ = http.NewRequest("GET", "http://example.com/api/v2/widgets", nil) w = httptest.NewRecorder() api.ServeHTTP(w, req) assert.Equal(w.Code, http.StatusBadRequest) assert.NotContains(w.Body.String(), "foo") }
func TestGzipHandler(t *testing.T) { testBody := "aaabbbccc" // This just exists to provide something for GzipHandler to wrap. handler := newTestHandler(testBody) // requests without accept-encoding are passed along as-is req1, _ := http.NewRequest("GET", "/whatever", nil) res1 := httptest.NewRecorder() handler.ServeHTTP(res1, req1) assert.Equal(t, 200, res1.Code) assert.Equal(t, "", res1.Header().Get("Content-Encoding")) assert.Equal(t, "Accept-Encoding", res1.Header().Get("Vary")) assert.Equal(t, testBody, res1.Body.String()) // but requests with accept-encoding:gzip are compressed if possible req2, _ := http.NewRequest("GET", "/whatever", nil) req2.Header.Set("Accept-Encoding", "gzip") res2 := httptest.NewRecorder() handler.ServeHTTP(res2, req2) assert.Equal(t, 200, res2.Code) assert.Equal(t, "gzip", res2.Header().Get("Content-Encoding")) assert.Equal(t, "Accept-Encoding", res2.Header().Get("Vary")) assert.Equal(t, gzipStr(testBody), res2.Body.Bytes()) }
func (s *daemonSuite) TestCommandMethodDispatch(c *check.C) { cmd := &Command{d: newTestDaemon(c)} mck := &mockHandler{cmd: cmd} rf := mkRF(c, cmd, mck) cmd.GET = rf cmd.PUT = rf cmd.POST = rf cmd.DELETE = rf for _, method := range []string{"GET", "POST", "PUT", "DELETE"} { req, err := http.NewRequest(method, "", nil) c.Assert(err, check.IsNil) rec := httptest.NewRecorder() cmd.ServeHTTP(rec, req) c.Check(rec.Code, check.Equals, http.StatusUnauthorized, check.Commentf(method)) rec = httptest.NewRecorder() req.RemoteAddr = "uid=0;" + req.RemoteAddr cmd.ServeHTTP(rec, req) c.Check(mck.lastMethod, check.Equals, method) c.Check(rec.Code, check.Equals, http.StatusOK) } req, err := http.NewRequest("POTATO", "", nil) c.Assert(err, check.IsNil) req.RemoteAddr = "uid=0;" + req.RemoteAddr rec := httptest.NewRecorder() cmd.ServeHTTP(rec, req) c.Check(rec.Code, check.Equals, http.StatusMethodNotAllowed) }
func Test_Flash(t *testing.T) { Convey("Test flash", t, func() { m := macaron.New() m.Use(Sessioner()) m.Get("/set", func(f *Flash) string { f.Success("success") f.Error("error") f.Warning("warning") f.Info("info") return "" }) m.Get("/get", func() {}) resp := httptest.NewRecorder() req, err := http.NewRequest("GET", "/set", nil) So(err, ShouldBeNil) m.ServeHTTP(resp, req) resp = httptest.NewRecorder() req, err = http.NewRequest("GET", "/get", nil) So(err, ShouldBeNil) req.Header.Set("Cookie", "macaron_flash=error%3Derror%26info%3Dinfo%26success%3Dsuccess%26warning%3Dwarning; Path=/") m.ServeHTTP(resp, req) }) }
func TestGeneratorRESTfulVerbs(t *testing.T) { handler, _ := NewHandler(CSRValidate) ts := httptest.NewServer(handler) data := csrData(t) // POST should work. req, _ := http.NewRequest("POST", ts.URL, data) resp, _ := http.DefaultClient.Do(req) if resp.StatusCode != http.StatusOK { t.Fatal(resp.Status) } // Test GET, PUT, DELETE and whatever, expect 400 errors. req, _ = http.NewRequest("GET", ts.URL, data) resp, _ = http.DefaultClient.Do(req) if resp.StatusCode != http.StatusMethodNotAllowed { t.Fatal(resp.Status) } req, _ = http.NewRequest("PUT", ts.URL, data) resp, _ = http.DefaultClient.Do(req) if resp.StatusCode != http.StatusMethodNotAllowed { t.Fatal(resp.Status) } req, _ = http.NewRequest("DELETE", ts.URL, data) resp, _ = http.DefaultClient.Do(req) if resp.StatusCode != http.StatusMethodNotAllowed { t.Fatal(resp.Status) } req, _ = http.NewRequest("WHATEVER", ts.URL, data) resp, _ = http.DefaultClient.Do(req) if resp.StatusCode != http.StatusMethodNotAllowed { t.Fatal(resp.Status) } }
// createRequest creates instance of http.Request containing all config // values and URL from current client and provided body. func createRequest(cl *Client, data io.Reader) (r *http.Request, err error) { url, err := createUrl(cl) if err != nil { return nil, err } var req *http.Request if data != nil { if req, err = http.NewRequest(cl.request.method, url.String(), data); err != nil { return nil, err } } else { if req, err = http.NewRequest(cl.request.method, url.String(), nil); err != nil { return nil, err } } for key, val := range cl.Headers { req.Header.Set(key, val) } if req.Header.Get(HeaderUserAgent) == "" { req.Header.Set(HeaderUserAgent, defaultUserAgentHeader) } if req.Header.Get(HeaderContentType) == "" { req.Header.Set(HeaderContentType, defaultContentType) } if req.Header.Get(HeaderAccept) == "" { req.Header.Set(HeaderAccept, defaultAcceptHeader) } return req, nil }
func (c *Client) newAuthenticatedRequest(urlToken string, values url.Values) (*http.Request, error) { var req *http.Request var err error switch c.authMethod { case AuthMethodClientSecretPost: values.Set("client_secret", c.creds.Secret) req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode())) if err != nil { return nil, err } case AuthMethodClientSecretBasic: req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode())) if err != nil { return nil, err } encodedID := url.QueryEscape(c.creds.ID) encodedSecret := url.QueryEscape(c.creds.Secret) req.SetBasicAuth(encodedID, encodedSecret) default: panic("misconfigured client: auth method not supported") } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") return req, nil }
func TestGzip(t *testing.T) { req, _ := http.NewRequest(vodka.GET, "/", nil) rec := httptest.NewRecorder() c := vodka.NewContext(req, vodka.NewResponse(rec), vodka.New()) h := func(c *vodka.Context) error { c.Response().Write([]byte("test")) // For 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(vodka.GET, "/", nil) req.Header.Set(vodka.AcceptEncoding, "gzip") rec = httptest.NewRecorder() c = vodka.NewContext(req, vodka.NewResponse(rec), vodka.New()) // Gzip Gzip()(h)(c) assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, "gzip", rec.Header().Get(vodka.ContentEncoding)) assert.Contains(t, rec.Header().Get(vodka.ContentType), vodka.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()) } }
func TestPrepareMultiFailures(t *testing.T) { server := DockerServer{multiFailures: []map[string]string{}} server.buildMuxer() errorID := "multi error" server.PrepareMultiFailures(errorID, "containers/json") server.PrepareMultiFailures(errorID, "containers/json") recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } if recorder.Body.String() != errorID+"\n" { t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) } recorder = httptest.NewRecorder() request, _ = http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } if recorder.Body.String() != errorID+"\n" { t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) } recorder = httptest.NewRecorder() request, _ = http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } if recorder.Body.String() == errorID+"\n" { t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) } }
func (l *localnet) SetConfig(config string) error { server := l.Servers()[0] req, err := http.NewRequest("GET", fmt.Sprintf("https://%s/config", server), nil) if err != nil { return err } resp, err := robusthttp.Client(l.NetworkPassword, true).Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("Expected HTTP OK, got %v", resp.Status) } req, err = http.NewRequest("POST", fmt.Sprintf("https://%s/config", server), bytes.NewBuffer([]byte(config))) if err != nil { return err } req.Header.Set("X-RobustIRC-Config-Revision", resp.Header.Get("X-RobustIRC-Config-Revision")) resp, err = robusthttp.Client(l.NetworkPassword, true).Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("Expected HTTP OK, got %v", resp.Status) } return nil }