Example #1
1
func buildTestRequest(method string, path string, body string, headers map[string][]string, cookies []*http.Cookie) *http.Request {
	host := "127.0.0.1"
	port := "80"
	rawurl := "http://" + host + ":" + port + path
	url_, _ := url.Parse(rawurl)
	proto := "HTTP/1.1"

	if headers == nil {
		headers = map[string][]string{}
	}

	headers["User-Agent"] = []string{"web.go test"}
	if method == "POST" {
		headers["Content-Length"] = []string{fmt.Sprintf("%d", len(body))}
		if headers["Content-Type"] == nil {
			headers["Content-Type"] = []string{"text/plain"}
		}
	}

	req := http.Request{Method: method,
		URL:    url_,
		Proto:  proto,
		Host:   host,
		Header: http.Header(headers),
		Body:   ioutil.NopCloser(bytes.NewBufferString(body)),
	}

	for _, cookie := range cookies {
		req.AddCookie(cookie)
	}
	return &req
}
Example #2
0
func handler(res http.ResponseWriter, req *http.Request) {
	res.Header().Set("Content-Type", "text/html; charset=utf-8")

	segs := strings.Split(strings.Trim(req.URL.Path, "/\\"), "/")
	if len(segs) < 2 {
		http.NotFound(res, req)
		return
	}
	params := []reflect.Value{}

	if len(segs) > 2 {
		for _, param := range segs[2:3] {
			params = append(params, reflect.ValueOf(param))
		}
	} else {
		params = append(params, reflect.ValueOf("Campari"))
	}

	switch segs[0] {
	case "welcome":
		controller := controllers.Welcome{res, req}
		action := helpers.Capitalize(segs[1])
		method := reflect.ValueOf(&controller).MethodByName(action)
		if method.IsValid() {
			method.Call(params)
		} else {
			http.NotFound(res, req)
		}
		break
	default:
		http.NotFound(res, req)
	}
}
Example #3
0
func (b *body) readTrailer() error {
	// The common case, since nobody uses trailers.
	buf, _ := b.r.Peek(2)
	if bytes.Equal(buf, singleCRLF) {
		b.r.ReadByte()
		b.r.ReadByte()
		return nil
	}

	// Make sure there's a header terminator coming up, to prevent
	// a DoS with an unbounded size Trailer.  It's not easy to
	// slip in a LimitReader here, as textproto.NewReader requires
	// a concrete *bufio.Reader.  Also, we can't get all the way
	// back up to our conn's LimitedReader that *might* be backing
	// this bufio.Reader.  Instead, a hack: we iteratively Peek up
	// to the bufio.Reader's max size, looking for a double CRLF.
	// This limits the trailer to the underlying buffer size, typically 4kB.
	if !seeUpcomingDoubleCRLF(b.r) {
		return errors.New("http: suspiciously long trailer after chunked body")
	}

	hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
	if err != nil {
		return err
	}
	switch rr := b.hdr.(type) {
	case *http.Request:
		rr.Trailer = http.Header(hdr)
	case *http.Response:
		rr.Trailer = http.Header(hdr)
	}
	return nil
}
Example #4
0
func TestResponseContentTypeInvalid(t *testing.T) {
	reporter := newMockReporter(t)

	headers1 := map[string][]string{
		"Content-Type": {";"},
	}

	headers2 := map[string][]string{
		"Content-Type": {"charset=utf-8"},
	}

	resp1 := NewResponse(reporter, &http.Response{
		Header: http.Header(headers1),
	})

	resp2 := NewResponse(reporter, &http.Response{
		Header: http.Header(headers2),
	})

	resp1.ContentType("")
	resp1.chain.assertFailed(t)
	resp1.chain.reset()

	resp1.ContentType("", "")
	resp1.chain.assertFailed(t)
	resp1.chain.reset()

	resp2.ContentType("")
	resp2.chain.assertFailed(t)
	resp2.chain.reset()

	resp2.ContentType("", "")
	resp2.chain.assertFailed(t)
	resp2.chain.reset()
}
Example #5
0
func TestRemoveSingleHopHeaders(t *testing.T) {
	hdr := http.Header(map[string][]string{
		// single-hop headers that should be removed
		"Connection":          []string{"close"},
		"Keep-Alive":          []string{"foo"},
		"Proxy-Authenticate":  []string{"Basic realm=example.com"},
		"Proxy-Authorization": []string{"foo"},
		"Te":                []string{"deflate,gzip"},
		"Trailers":          []string{"ETag"},
		"Transfer-Encoding": []string{"chunked"},
		"Upgrade":           []string{"WebSocket"},

		// headers that should persist
		"Accept": []string{"application/json"},
		"X-Foo":  []string{"Bar"},
	})

	removeSingleHopHeaders(&hdr)

	want := http.Header(map[string][]string{
		"Accept": []string{"application/json"},
		"X-Foo":  []string{"Bar"},
	})

	if !reflect.DeepEqual(want, hdr) {
		t.Fatalf("unexpected result: want = %#v, got = %#v", want, hdr)
	}
}
Example #6
0
func noConfusion(res http.ResponseWriter, req *http.Request) {

	var html string

	if req.Method == "POST" {

		// get cookie value
		cookie, _ := req.Cookie("session-id")
		id := ???
		if cookie != nil {
			html += `
			<br>
			<p>Value from cookie: ` + id + `</p>
			`
		}

		// get memcache value
		ctx := appengine.NewContext(req)
		item, _ := memcache.Get(ctx, id)
		if item != nil {
			html += `
			<br>
			<p>
			Value from memcache: ` + string(item.Value) + `
			</p>
		`
		}
	}
	res.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(res, html)
}s
Example #7
0
func tarGzHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)

	files := vars["files"]

	tarfilename := fmt.Sprintf("transfersh-%d.tar.gz", uint16(time.Now().UnixNano()))

	w.Header().Set("Content-Type", "application/x-gzip")
	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", tarfilename))
	w.Header().Set("Connection", "close")

	os := gzip.NewWriter(w)
	defer os.Close()

	zw := tar.NewWriter(os)
	defer zw.Close()

	for _, key := range strings.Split(files, ",") {
		if strings.HasPrefix(key, "/") {
			key = key[1:]
		}

		key = strings.Replace(key, "\\", "/", -1)

		token := strings.Split(key, "/")[0]
		filename := sanitize.Path(strings.Split(key, "/")[1])

		reader, _, contentLength, err := storage.Get(token, filename)
		if err != nil {
			if err.Error() == "The specified key does not exist." {
				http.Error(w, "File not found", 404)
				return
			} else {
				log.Printf("%s", err.Error())
				http.Error(w, "Could not retrieve file.", 500)
				return
			}
		}

		defer reader.Close()

		header := &tar.Header{
			Name: strings.Split(key, "/")[1],
			Size: int64(contentLength),
		}

		err = zw.WriteHeader(header)
		if err != nil {
			log.Printf("%s", err.Error())
			http.Error(w, "Internal server error.", 500)
			return
		}

		if _, err = io.Copy(zw, reader); err != nil {
			log.Printf("%s", err.Error())
			http.Error(w, "Internal server error.", 500)
			return
		}
	}
}
Example #8
0
func addTestManifest(repo reference.Named, reference string, mediatype string, content []byte, m *testutil.RequestResponseMap) {
	*m = append(*m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "GET",
			Route:  "/v2/" + repo.Name() + "/manifests/" + reference,
		},
		Response: testutil.Response{
			StatusCode: http.StatusOK,
			Body:       content,
			Headers: http.Header(map[string][]string{
				"Content-Length":        {fmt.Sprint(len(content))},
				"Last-Modified":         {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
				"Content-Type":          {mediatype},
				"Docker-Content-Digest": {contentDigestString(mediatype, content)},
			}),
		},
	})
	*m = append(*m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "HEAD",
			Route:  "/v2/" + repo.Name() + "/manifests/" + reference,
		},
		Response: testutil.Response{
			StatusCode: http.StatusOK,
			Headers: http.Header(map[string][]string{
				"Content-Length":        {fmt.Sprint(len(content))},
				"Last-Modified":         {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
				"Content-Type":          {mediatype},
				"Docker-Content-Digest": {digest.Canonical.FromBytes(content).String()},
			}),
		},
	})

}
Example #9
0
func addTestManifestWithEtag(repo, reference string, content []byte, m *testutil.RequestResponseMap, dgst string) {
	actualDigest, _ := digest.FromBytes(content)
	getReqWithEtag := testutil.Request{
		Method: "GET",
		Route:  "/v2/" + repo + "/manifests/" + reference,
		Headers: http.Header(map[string][]string{
			"If-None-Match": {fmt.Sprintf(`"%s"`, dgst)},
		}),
	}

	var getRespWithEtag testutil.Response
	if actualDigest.String() == dgst {
		getRespWithEtag = testutil.Response{
			StatusCode: http.StatusNotModified,
			Body:       []byte{},
			Headers: http.Header(map[string][]string{
				"Content-Length": {"0"},
				"Last-Modified":  {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
			}),
		}
	} else {
		getRespWithEtag = testutil.Response{
			StatusCode: http.StatusOK,
			Body:       content,
			Headers: http.Header(map[string][]string{
				"Content-Length": {fmt.Sprint(len(content))},
				"Last-Modified":  {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
			}),
		}

	}
	*m = append(*m, testutil.RequestResponseMapping{Request: getReqWithEtag, Response: getRespWithEtag})
}
Example #10
0
func addTestManifest(repo, reference string, content []byte, m *testutil.RequestResponseMap) {
	*m = append(*m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "GET",
			Route:  "/v2/" + repo + "/manifests/" + reference,
		},
		Response: testutil.Response{
			StatusCode: http.StatusOK,
			Body:       content,
			Headers: http.Header(map[string][]string{
				"Content-Length": {fmt.Sprint(len(content))},
				"Last-Modified":  {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
			}),
		},
	})
	*m = append(*m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "HEAD",
			Route:  "/v2/" + repo + "/manifests/" + reference,
		},
		Response: testutil.Response{
			StatusCode: http.StatusOK,
			Headers: http.Header(map[string][]string{
				"Content-Length": {fmt.Sprint(len(content))},
				"Last-Modified":  {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
			}),
		},
	})

}
Example #11
0
func TestBlobMount(t *testing.T) {
	dgst, content := newRandomBlob(1024)
	var m testutil.RequestResponseMap
	repo := "test.example.com/uploadrepo"
	sourceRepo := "test.example.com/sourcerepo"
	m = append(m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method:      "POST",
			Route:       "/v2/" + repo + "/blobs/uploads/",
			QueryParams: map[string][]string{"from": {sourceRepo}, "mount": {dgst.String()}},
		},
		Response: testutil.Response{
			StatusCode: http.StatusCreated,
			Headers: http.Header(map[string][]string{
				"Content-Length":        {"0"},
				"Location":              {"/v2/" + repo + "/blobs/" + dgst.String()},
				"Docker-Content-Digest": {dgst.String()},
			}),
		},
	})
	m = append(m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "HEAD",
			Route:  "/v2/" + repo + "/blobs/" + dgst.String(),
		},
		Response: testutil.Response{
			StatusCode: http.StatusOK,
			Headers: http.Header(map[string][]string{
				"Content-Length": {fmt.Sprint(len(content))},
				"Last-Modified":  {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
			}),
		},
	})

	e, c := testServer(m)
	defer c()

	ctx := context.Background()
	r, err := NewRepository(ctx, repo, e, nil)
	if err != nil {
		t.Fatal(err)
	}

	l := r.Blobs(ctx)

	stat, err := l.Mount(ctx, sourceRepo, dgst)
	if err != nil {
		t.Fatal(err)
	}

	if stat.Digest != dgst {
		t.Fatalf("Unexpected digest: %s, expected %s", stat.Digest, dgst)
	}
}
Example #12
0
func gamepage(w http.ResponseWriter, r *http.Request) {
    cookie, _ := r.Cookie("Spanzhash")
    if(hashExists(cookie.Name))
	data, err := ioutil.ReadFile("./layouts/gamepage.html")
    if err==nil {
    	w.Header().Add("Content-Type","text/html")
    	w.Write(data)
    } else {
    	w.WriteHeader(404)
    	w.Write([]byte("404 Page not found - "+http.StatusText(404)))
    }
}
Example #13
0
func TestBlobExistsNoContentLength(t *testing.T) {
	var m testutil.RequestResponseMap

	repo, _ := reference.ParseNamed("biff")
	dgst, content := newRandomBlob(1024)
	m = append(m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "GET",
			Route:  "/v2/" + repo.Name() + "/blobs/" + dgst.String(),
		},
		Response: testutil.Response{
			StatusCode: http.StatusOK,
			Body:       content,
			Headers: http.Header(map[string][]string{
				//			"Content-Length": {fmt.Sprint(len(content))},
				"Last-Modified": {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
			}),
		},
	})

	m = append(m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "HEAD",
			Route:  "/v2/" + repo.Name() + "/blobs/" + dgst.String(),
		},
		Response: testutil.Response{
			StatusCode: http.StatusOK,
			Headers: http.Header(map[string][]string{
				//			"Content-Length": {fmt.Sprint(len(content))},
				"Last-Modified": {time.Now().Add(-1 * time.Second).Format(time.ANSIC)},
			}),
		},
	})
	e, c := testServer(m)
	defer c()

	ctx := context.Background()
	r, err := NewRepository(ctx, repo, e, nil)
	if err != nil {
		t.Fatal(err)
	}
	l := r.Blobs(ctx)

	_, err = l.Stat(ctx, dgst)
	if err == nil {
		t.Fatal(err)
	}
	if !strings.Contains(err.Error(), "missing content-length heade") {
		t.Fatalf("Expected missing content-length error message")
	}

}
Example #14
0
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	data, _ := json.Marshal([]string{"San Francisco", "Amsterdam",
	"Berlin","Palo Alto", "Los Altos})
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Write(data)
}

func main() {
	http.HandleFunc("/", HomeHandler)
	err := http.ListenAndServe(":"+os.Getenv("PORT"), nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Example #15
0
// This test takes ~1 seconds to run
func TestRatelimitGlobal(t *testing.T) {
	rl := NewRatelimiter()

	sendReq := func(endpoint string) {
		bucket := rl.LockBucket(endpoint)

		headers := http.Header(make(map[string][]string))

		headers.Set("X-RateLimit-Global", "1")
		// Reset for approx 1 seconds from now
		headers.Set("Retry-After", "1000")

		err := bucket.Release(headers)
		if err != nil {
			t.Errorf("Release returned error: %v", err)
		}
	}

	sent := time.Now()

	// This should trigger a global ratelimit
	sendReq("/guilds/99/channels")
	time.Sleep(time.Millisecond * 100)

	// This shouldn't go through in less than 1 second
	sendReq("/guilds/55/channels")

	if time.Since(sent) >= time.Second && time.Since(sent) < time.Second*2 {
		t.Log("OK", time.Since(sent))
	} else {
		t.Error("Did not ratelimit correctly, got:", time.Since(sent))
	}
}
Example #16
0
// ImageBuild sends request to the daemon to build images.
// The Body in the response implement an io.ReadCloser and it's up to the caller to
// close it.
func (cli *Client) ImageBuild(ctx context.Context, buildContext io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) {
	query, err := imageBuildOptionsToQuery(options)
	if err != nil {
		return types.ImageBuildResponse{}, err
	}

	headers := http.Header(make(map[string][]string))
	buf, err := json.Marshal(options.AuthConfigs)
	if err != nil {
		return types.ImageBuildResponse{}, err
	}
	headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf))
	headers.Set("Content-Type", "application/tar")

	serverResp, err := cli.postRaw(ctx, "/build", query, buildContext, headers)
	if err != nil {
		return types.ImageBuildResponse{}, err
	}

	osType := getDockerOS(serverResp.header.Get("Server"))

	return types.ImageBuildResponse{
		Body:   serverResp.body,
		OSType: osType,
	}, nil
}
Example #17
0
func prepTemplate(parent *template.Template, fn, base string) error {
	t := parent.New(base)

	f, err := os.Open(fn)
	if err != nil {
		return err
	}
	defer f.Close()

	msg, err := mail.ReadMessage(f)
	if err != nil {
		return err
	}

	for k, v := range defaultHeaders {
		if msg.Header.Get(k) == "" {
			msg.Header[k] = v
		}
	}

	data := &bytes.Buffer{}

	// This is the only place I could find this method.  :/
	http.Header(msg.Header).Write(data)
	data.Write([]byte{'\r', '\n'})

	_, err = io.Copy(data, msg.Body)
	if err != nil {
		return err
	}

	_, err = t.Parse(data.String())
	return err
}
Example #18
0
func TestAuthBasic(t *testing.T) {
	secrets := HtpasswdFileProvider("test.htpasswd")

	for _, isProxy := range []bool{false, true} {
		a := &BasicAuth{IsProxy: isProxy, Realm: "example.com", Secrets: secrets}
		r := &http.Request{}
		r.Method = "GET"
		if a.CheckAuth(r) != "" {
			t.Fatal("CheckAuth passed on empty headers")
		}
		r.Header = http.Header(make(map[string][]string))
		r.Header.Set(AuthorizationHeaderName(a.IsProxy), "Digest blabla ololo")
		if a.CheckAuth(r) != "" {
			t.Fatal("CheckAuth passed on bad headers")
		}
		r.Header.Set(AuthorizationHeaderName(a.IsProxy), "Basic !@#")
		if a.CheckAuth(r) != "" {
			t.Fatal("CheckAuth passed on bad base64 data")
		}

		data := [][]string{
			{"test", "hello"},
			{"test2", "hello2"},
			{"test3", "hello3"},
			{"test16", "topsecret"},
		}
		for _, tc := range data {
			auth := base64.StdEncoding.EncodeToString([]byte(tc[0] + ":" + tc[1]))
			r.Header.Set(AuthorizationHeaderName(a.IsProxy), "Basic "+auth)
			if a.CheckAuth(r) != tc[0] {
				t.Fatalf("CheckAuth failed for user '%s'", tc[0])
			}
		}
	}
}
func TestManifestPut(t *testing.T) {
	repo := "test.example.com/repo/delete"
	m1, dgst := newRandomSchemaV1Manifest(repo, "other", 6)
	var m testutil.RequestResponseMap
	m = append(m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "PUT",
			Route:  "/v2/" + repo + "/manifests/other",
			Body:   m1.Raw,
		},
		Response: testutil.Response{
			StatusCode: http.StatusAccepted,
			Headers: http.Header(map[string][]string{
				"Content-Length":        {"0"},
				"Docker-Content-Digest": {dgst.String()},
			}),
		},
	})

	e, c := testServer(m)
	defer c()

	r, err := NewRepository(context.Background(), repo, e, nil)
	if err != nil {
		t.Fatal(err)
	}

	ms := r.Manifests()
	if err := ms.Put(m1); err != nil {
		t.Fatal(err)
	}

	// TODO(dmcgowan): Check for invalid input error
}
Example #20
0
func TestErrorWriteTo(t *testing.T) {
	for k, _ := range errors {
		err := NewError(k, "", 1)
		rr := httptest.NewRecorder()
		err.WriteTo(rr)

		if err.statusCode() != rr.Code {
			t.Errorf("HTTP status code %d, want %d", rr.Code, err.statusCode())
		}

		gbody := strings.TrimSuffix(rr.Body.String(), "\n")
		if err.toJsonString() != gbody {
			t.Errorf("HTTP body %q, want %q", gbody, err.toJsonString())
		}

		wheader := http.Header(map[string][]string{
			"Content-Type": []string{"application/json"},
			"X-Etcd-Index": []string{"1"},
		})

		if !reflect.DeepEqual(wheader, rr.HeaderMap) {
			t.Errorf("HTTP headers %v, want %v", rr.HeaderMap, wheader)
		}
	}

}
Example #21
0
func TestBlobDelete(t *testing.T) {
	dgst, _ := newRandomBlob(1024)
	var m testutil.RequestResponseMap
	repo := "test.example.com/repo1"
	m = append(m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "DELETE",
			Route:  "/v2/" + repo + "/blobs/" + dgst.String(),
		},
		Response: testutil.Response{
			StatusCode: http.StatusAccepted,
			Headers: http.Header(map[string][]string{
				"Content-Length": {"0"},
			}),
		},
	})

	e, c := testServer(m)
	defer c()

	ctx := context.Background()
	r, err := NewRepository(ctx, repo, e, nil)
	if err != nil {
		t.Fatal(err)
	}
	l := r.Blobs(ctx)
	err = l.Delete(ctx, dgst)
	if err != nil {
		t.Errorf("Error deleting blob: %s", err.Error())
	}

}
Example #22
0
// Search queries the public registry for images matching the specified
// search terms, and returns the results.
func (s *Service) Search(term string, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) {
	if err := validateNoSchema(term); err != nil {
		return nil, err
	}

	indexName, remoteName := splitReposSearchTerm(term)

	index, err := newIndexInfo(s.config, indexName)
	if err != nil {
		return nil, err
	}

	// *TODO: Search multiple indexes.
	endpoint, err := NewV1Endpoint(index, userAgent, http.Header(headers))
	if err != nil {
		return nil, err
	}

	r, err := NewSession(endpoint.client, authConfig, endpoint)
	if err != nil {
		return nil, err
	}

	if index.Official {
		localName := remoteName
		if strings.HasPrefix(localName, "library/") {
			// If pull "library/foo", it's stored locally under "foo"
			localName = strings.SplitN(localName, "/", 2)[1]
		}

		return r.SearchRepositories(localName)
	}
	return r.SearchRepositories(remoteName)
}
Example #23
0
File: ssdp.go Project: ronindev/dms
func ReadRequest(b *bufio.Reader) (req *http.Request, err error) {
	tp := textproto.NewReader(b)
	var s string
	if s, err = tp.ReadLine(); err != nil {
		return nil, err
	}
	defer func() {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
	}()

	var f []string
	// TODO a split that only allows N values?
	if f = strings.SplitN(s, " ", 3); len(f) < 3 {
		return nil, &badStringError{"malformed request line", s}
	}
	if f[1] != "*" {
		return nil, &badStringError{"bad URL request", f[1]}
	}
	req = &http.Request{
		Method: f[0],
	}
	var ok bool
	if req.ProtoMajor, req.ProtoMinor, ok = http.ParseHTTPVersion(strings.TrimSpace(f[2])); !ok {
		return nil, &badStringError{"malformed HTTP version", f[2]}
	}

	mimeHeader, err := tp.ReadMIMEHeader()
	if err != nil {
		return nil, err
	}
	req.Header = http.Header(mimeHeader)
	return
}
Example #24
0
// Request returns a HTTP Response with Header and Body
// from fcgi responder
func (this *FCGIClient) Request(p map[string]string, req io.Reader) (resp *http.Response, err error) {

	r, err := this.Do(p, req)
	if err != nil {
		return
	}

	rb := bufio.NewReader(r)
	tp := textproto.NewReader(rb)
	resp = new(http.Response)

	// Parse the response headers.
	mimeHeader, err := tp.ReadMIMEHeader()
	if err != nil {
		return
	}
	resp.Header = http.Header(mimeHeader)

	// TODO: fixTransferEncoding ?
	resp.TransferEncoding = resp.Header["Transfer-Encoding"]
	resp.ContentLength, _ = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)

	if chunked(resp.TransferEncoding) {
		resp.Body = ioutil.NopCloser(httputil.NewChunkedReader(rb))
	} else {
		resp.Body = ioutil.NopCloser(rb)
	}

	return
}
Example #25
0
func TestHTTPErrorWriteTo(t *testing.T) {
	err := NewHTTPError(http.StatusBadRequest, "what a bad request you made!")
	rr := httptest.NewRecorder()
	if e := err.WriteTo(rr); e != nil {
		t.Fatalf("HTTPError.WriteTo error (%v)", e)
	}

	wcode := http.StatusBadRequest
	wheader := http.Header(map[string][]string{
		"Content-Type": {"application/json"},
	})
	wbody := `{"message":"what a bad request you made!"}`

	if wcode != rr.Code {
		t.Errorf("HTTP status code %d, want %d", rr.Code, wcode)
	}

	if !reflect.DeepEqual(wheader, rr.HeaderMap) {
		t.Errorf("HTTP headers %v, want %v", rr.HeaderMap, wheader)
	}

	gbody := rr.Body.String()
	if wbody != gbody {
		t.Errorf("HTTP body %q, want %q", gbody, wbody)
	}
}
Example #26
0
func getResponse(code int, body string) *http.Response {
	var resp = &http.Response{}
	resp.Body = NewBody(body)
	resp.Header = http.Header(map[string][]string{})
	resp.StatusCode = code
	return resp
}
func TestManifestDelete(t *testing.T) {
	repo := "test.example.com/repo/delete"
	_, dgst1 := newRandomSchemaV1Manifest(repo, "latest", 6)
	_, dgst2 := newRandomSchemaV1Manifest(repo, "latest", 6)
	var m testutil.RequestResponseMap
	m = append(m, testutil.RequestResponseMapping{
		Request: testutil.Request{
			Method: "DELETE",
			Route:  "/v2/" + repo + "/manifests/" + dgst1.String(),
		},
		Response: testutil.Response{
			StatusCode: http.StatusOK,
			Headers: http.Header(map[string][]string{
				"Content-Length": {"0"},
			}),
		},
	})

	e, c := testServer(m)
	defer c()

	r, err := NewRepository(context.Background(), repo, e, nil)
	if err != nil {
		t.Fatal(err)
	}

	ms := r.Manifests()
	if err := ms.Delete(dgst1); err != nil {
		t.Fatal(err)
	}
	if err := ms.Delete(dgst2); err == nil {
		t.Fatal("Expected error deleting unknown manifest")
	}
	// TODO(dmcgowan): Check for specific unknown error
}
Example #28
0
func TestResponseJSONPBadBody(t *testing.T) {
	reporter := newMockReporter(t)

	headers := map[string][]string{
		"Content-Type": {"application/javascript; charset=utf-8"},
	}

	body1 := `foo`
	body2 := `foo();`
	body3 := `foo(`
	body4 := `foo({);`

	for _, body := range []string{body1, body2, body3, body4} {
		httpResp := &http.Response{
			StatusCode: http.StatusOK,
			Header:     http.Header(headers),
			Body:       ioutil.NopCloser(bytes.NewBufferString(body)),
		}

		resp := NewResponse(reporter, httpResp)

		resp.JSONP("foo")
		resp.chain.assertFailed(t)
		resp.chain.reset()

		assert.True(t, resp.JSONP("foo").Raw() == nil)
	}
}
Example #29
0
func TestSendError(t *testing.T) {
	for i, tc := range []struct {
		Code int
		Err  error
		Body string
	}{
		{http.StatusInternalServerError, fmt.Errorf("ERR"),
			"ERR\n"},
		{3, HTTPError{Err: nil, Code: 3}, "\n"},
		{3, HTTPError{Err: fmt.Errorf("bad status code"), Code: 3}, "bad status code\n"},
		{500, HTTPErrorCode{Err: nil, StatusCode: "418 I'm not a Teapot"},
			`{"error":{"code":"418 I'm not a Teapot","message":"","status":500}}`},
		{500, HTTPErrorCode{Err: fmt.Errorf("something happened"), StatusCode: "418 I'm not a Teapot"},
			`{"error":{"code":"418 I'm not a Teapot","message":"something happened","status":500}}`},
	} {
		rr := httptest.NewRecorder()
		var hdr http.Header
		if _, ok := tc.Err.(HTTPErrorCode); ok {
			hdr = http.Header(map[string][]string{"Accept": {"application/json"}})
		}
		sendError(rr, &http.Request{URL: &url.URL{}, Header: hdr}, tc.Err)
		if rr.Code != tc.Code {
			t.Errorf("%d. got %d, want %d for %#v.", i, rr.Code, tc.Code, tc.Err)
		}
		got := rr.Body.String()
		if got != tc.Body {
			t.Errorf("%d. got %q, want %q for %v.", i, got, tc.Body, tc.Err)
		}
	}
}
Example #30
0
func TestResponseNoContentFailed(t *testing.T) {
	reporter := newMockReporter(t)

	headers := map[string][]string{
		"Content-Type": {"text/plain; charset=utf-8"},
	}

	body := ``

	httpResp := &http.Response{
		StatusCode: http.StatusOK,
		Header:     http.Header(headers),
		Body:       ioutil.NopCloser(bytes.NewBufferString(body)),
	}

	resp := NewResponse(reporter, httpResp)

	assert.Equal(t, body, resp.Body().Raw())
	resp.chain.assertOK(t)
	resp.chain.reset()

	resp.NoContent()
	resp.chain.assertFailed(t)
	resp.chain.reset()
}