Golang Header示例

说明

golang header示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net/http

示例#1
文件: web_test.go 项目: stinkyfingers/web

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
}

示例#2
文件: main.go 项目: hayate/campari

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)
	}
}

示例#3
文件: transfer.go 项目: fdr/roundtripper

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
}

示例#4
文件: response_test.go 项目: stellar/bridge-server

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()
}

示例#5
文件: reverse_test.go 项目: b2ornot2b/etcd

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)
	}
}

示例#6
文件: exampleMemCache.go 项目: xolejh/WebDev

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

示例#7
文件: handlers.go 项目: diegslva/transfer.sh

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
		}
	}
}

示例#8
文件: repository_test.go 项目: CowLeo/distribution

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()},
			}),
		},
	})

}

示例#9
文件: repository_test.go 项目: nateww/distribution

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})
}

示例#10
文件: repository_test.go 项目: nateww/distribution

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)},
			}),
		},
	})

}

示例#11
文件: repository_test.go 项目: toby82/distribution

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)
	}
}

示例#12
文件: main.go 项目: whitehood15/proectinfo

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)))
    }
}

示例#13
文件: repository_test.go 项目: CowLeo/distribution

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")
	}

}

示例#14
文件: main.go 项目: mies/gettingstarted-golang

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)
	}
}

示例#15
文件: ratelimit_test.go 项目: bwmarrin/discordgo

// 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))
	}
}

示例#16
文件: image_build.go 项目: CadeLaRen/docker-3

// 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
}

示例#17
文件: email.go 项目: jk-cbfs/cbugg

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
}

示例#18
文件: basic_test.go 项目: kmanley/go-http-auth

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 [email protected]#")
		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])
			}
		}
	}
}

示例#19
文件: repository_test.go 项目: denverdino/distribution-fuse

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
}

示例#20
文件: error_test.go 项目: diffoperator/etcd

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)
		}
	}

}

示例#21
文件: repository_test.go 项目: nateww/distribution

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())
	}

}

示例#22
文件: service.go 项目: DCdrone/docker

// 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)
}

示例#23
文件: ssdp.go 项目: 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
}

示例#24
文件: fcgiclient.go 项目: andviro/fcgi_client

// 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
}

示例#25
文件: errors_test.go 项目: CliffYuan/etcd

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)
	}
}

示例#26
文件: models_test.go 项目: lofdev/twittergo

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
}

示例#27
文件: repository_test.go 项目: denverdino/distribution-fuse

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
}

示例#28
文件: response_test.go 项目: stellar/bridge-server

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)
	}
}

示例#29
文件: send_error_test.go 项目: patrickToca/httpctx

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)
		}
	}
}

示例#30
文件: response_test.go 项目: stellar/bridge-server

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()
}

展开阅读全文