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


Golang http.Header类代码示例

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


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

示例1: TestSampleWithRequestHeaders

func TestSampleWithRequestHeaders(t *testing.T) {
	var header http.Header

	handler := func(w http.ResponseWriter, r *http.Request) {
		header = r.Header

		fmt.Fprintf(w, "ok")
	}
	ts := httptest.NewServer(http.HandlerFunc(handler))
	defer ts.Close()

	target := Target{
		URL: parseUrl(ts.URL),
		RequestHeaders: map[string]string{
			"X-Foo": "bar",
		},
	}

	sample, err := Ping(target, 1)
	if err != nil {
		t.Fatal(err)
	}

	if sample.StatusCode != 200 {
		t.Fatalf("Expected sampleStatus == 200, but got %d\n", sample.StatusCode)
	}

	h := header.Get("X-Foo")
	if h != "bar" {
		t.Fatalf("Expected request header X-Foo to be 'bar' but was '%s'", h)
	}
}
开发者ID:linearregression,项目名称:canary-1,代码行数:32,代码来源:sampler_test.go

示例2: prepareReq

func (c *Client) prepareReq(method, rawurl string, header http.Header, in interface{}) (*http.Request, error) {
	var payload io.Reader
	switch v := in.(type) {
	case io.Reader:
		payload = v
	case nil:
	default:
		var err error
		payload, err = ToJSON(in)
		if err != nil {
			return nil, err
		}
	}

	req, err := http.NewRequest(method, rawurl, payload)
	if err != nil {
		return nil, err
	}
	if header == nil {
		header = make(http.Header)
	}
	if header.Get("Content-Type") == "" {
		header.Set("Content-Type", "application/json")
	}
	req.Header = header
	if c.Key != "" {
		req.SetBasicAuth("", c.Key)
	}
	if c.Host != "" {
		req.Host = c.Host
	}
	return req, nil
}
开发者ID:devick,项目名称:flynn,代码行数:33,代码来源:json.go

示例3: isContentType

// isContentType validates the Content-Type header
// is contentType. That is, its type and subtype match.
func isContentType(h http.Header, contentType string) bool {
	ct := h.Get("Content-Type")
	if i := strings.IndexRune(ct, ';'); i != -1 {
		ct = ct[0:i]
	}
	return ct == contentType
}
开发者ID:number9code,项目名称:dogestry,代码行数:9,代码来源:handlers.go

示例4: GetResponse

func (c *CacheItem) GetResponse() *http.Response {
	r := c.ResponseStates[c.currentState]
	if r.NextState != "" {
		logger.Debug("Switch from state \"" + c.currentState + "\" to state \"" + r.NextState + "\"")
		c.currentState = r.NextState
	}

	ret := c.dispatchReturn(r.Return)

	rbuf := httper.NewResponse(ret)
	code, _ := strconv.Atoi(rbuf.Header.Code)
	vMaj, _ := strconv.Atoi(rbuf.Header.Major)
	vMin, _ := strconv.Atoi(rbuf.Header.Minor)
	h := http.Header{}
	for _, v := range rbuf.Header.Headers {
		h.Add(v.Key, v.Value)
	}
	h.Add("X-Cacher", "In-The-Middle")

	resp := &http.Response{
		Status:     fmt.Sprintf("%s %s", rbuf.Header.Code, rbuf.Header.Message),
		StatusCode: code,
		Proto:      fmt.Sprintf("%s/%s", rbuf.Header.Protocol, rbuf.Header.Version),
		Header:     h,
		ProtoMajor: vMaj,
		ProtoMinor: vMin,
		Body:       ioutil.NopCloser(bytes.NewBufferString(rbuf.Payload)),
	}
	return resp
}
开发者ID:chonla,项目名称:in-the-middle,代码行数:30,代码来源:cache_element.go

示例5: createSubStream

func (s *Transport) createSubStream(parentID uint64) (*stream, error) {
	referenceID := atomic.AddUint64(&s.referenceCounter, 1)
	headers := http.Header{}
	headers.Set("libchan-ref", strconv.FormatUint(referenceID, 10))
	if parentID > 0 {
		headers.Set("libchan-parent-ref", strconv.FormatUint(parentID, 10))
	}

	providedStream, err := s.provider.NewStream(headers)
	if err != nil {
		return nil, err
	}

	newStream := &stream{
		referenceID: referenceID,
		parentID:    parentID,
		stream:      providedStream,
		session:     s,
	}

	// TODO: hold reference to the newly created stream
	// for possible cleanup. This stream should not be put
	// in the streams maps which holds remotely created
	// streams and will can have reference id conflicts.

	return newStream, nil

}
开发者ID:zhaohaidao,项目名称:libchan,代码行数:28,代码来源:session.go

示例6: TestWarning

func TestWarning(t *testing.T) {
	hdr := http.Header{}
	err := fmt.Errorf("modifier error")

	Warning(hdr, err)

	if got, want := len(hdr["Warning"]), 1; got != want {
		t.Fatalf("len(hdr[%q]): got %d, want %d", "Warning", got, want)
	}

	want := `199 "martian" "modifier error"`
	if got := hdr["Warning"][0]; !strings.HasPrefix(got, want) {
		t.Errorf("hdr[%q][0]: got %q, want to have prefix %q", "Warning", got, want)
	}

	hdr.Set("Date", "Mon, 02 Jan 2006 15:04:05 GMT")
	Warning(hdr, err)

	if got, want := len(hdr["Warning"]), 2; got != want {
		t.Fatalf("len(hdr[%q]): got %d, want %d", "Warning", got, want)
	}

	want = `199 "martian" "modifier error" "Mon, 02 Jan 2006 15:04:05 GMT"`
	if got := hdr["Warning"][1]; got != want {
		t.Errorf("hdr[%q][1]: got %q, want %q", "Warning", got, want)
	}
}
开发者ID:haijianren,项目名称:martian,代码行数:27,代码来源:proxyutil_test.go

示例7: createHeaders

func createHeaders(extraHeaders http.Header, credentials *auth.Credentials, contentType, rfc1123Date,
	apiVersion string, isMantaRequest bool) (http.Header, error) {

	headers := make(http.Header)
	if extraHeaders != nil {
		for header, values := range extraHeaders {
			for _, value := range values {
				headers.Add(header, value)
			}
		}
	}
	if extraHeaders.Get("Content-Type") == "" {
		headers.Add("Content-Type", contentType)
	}
	if extraHeaders.Get("Accept") == "" {
		headers.Add("Accept", contentType)
	}
	if rfc1123Date != "" {
		headers.Set("Date", rfc1123Date)
	} else {
		headers.Set("Date", getDateForRegion(credentials, isMantaRequest))
	}
	authHeaders, err := auth.CreateAuthorizationHeader(headers, credentials, isMantaRequest)
	if err != nil {
		return http.Header{}, err
	}
	headers.Set("Authorization", authHeaders)
	if apiVersion != "" {
		headers.Set("X-Api-Version", apiVersion)
	}
	headers.Add("User-Agent", gojoyentAgent())
	return headers, nil
}
开发者ID:asteris-llc,项目名称:gocommon,代码行数:33,代码来源:client.go

示例8: intHeader

func intHeader(key string, h http.Header) (int, error) {
	if header := h.Get(key); header != "" {
		return strconv.Atoi(header)
	} else {
		return 0, errNoHeader
	}
}
开发者ID:taliesins,项目名称:goproxy,代码行数:7,代码来源:header.go

示例9: copyHeader

func copyHeader(source http.Header, dest *http.Header) {
	for n, v := range source {
		for _, vv := range v {
			dest.Add(n, vv)
		}
	}
}
开发者ID:carriercomm,项目名称:gofana,代码行数:7,代码来源:main.go

示例10: cacheAge

func (p *proxyWriter) cacheAge(hdr http.Header, statusCode int) (int64, bool) {
	if _, ok := hdr["Set-Cookie"]; ok {
		return 0, false
	}
	if v := hdr.Get("Expires"); v != "" {
		t, err := time.Parse(http.TimeFormat, v)
		if err != nil || time.Now().After(t) {
			return 0, false
		}
	}
	if vals, ok := hdr["Cache-Control"]; ok {
		for _, v := range vals {
			fields := strings.Fields(v)
			for _, f := range fields {
				if f == "no-store" ||
					strings.HasPrefix(f, "no-cache") ||
					strings.HasPrefix(f, "private") {
					return 0, false
				}
				if strings.HasPrefix(f, "max-age=") {
					age, err := strconv.ParseInt(f[len("max-age="):], 10, 64)
					if err != nil || age <= 0 {
						return 0, false
					}
					return age, true
				}
			}
		}
	}
	return int64(p.c.age(statusCode) / time.Second), true
}
开发者ID:james4k,项目名称:cache,代码行数:31,代码来源:proxywriter.go

示例11: timeHeader

func timeHeader(key string, h http.Header) (time.Time, error) {
	if header := h.Get(key); header != "" {
		return http.ParseTime(header)
	} else {
		return time.Time{}, errNoHeader
	}
}
开发者ID:taliesins,项目名称:goproxy,代码行数:7,代码来源:header.go

示例12: ParseLXDFileHeaders

func ParseLXDFileHeaders(headers http.Header) (uid int, gid int, mode int, type_ string) {
	uid, err := strconv.Atoi(headers.Get("X-LXD-uid"))
	if err != nil {
		uid = -1
	}

	gid, err = strconv.Atoi(headers.Get("X-LXD-gid"))
	if err != nil {
		gid = -1
	}

	mode, err = strconv.Atoi(headers.Get("X-LXD-mode"))
	if err != nil {
		mode = -1
	} else {
		rawMode, err := strconv.ParseInt(headers.Get("X-LXD-mode"), 0, 0)
		if err == nil {
			mode = int(os.FileMode(rawMode) & os.ModePerm)
		}
	}

	type_ = headers.Get("X-LXD-type")
	/* backwards compat: before "type" was introduced, we could only
	 * manipulate files
	 */
	if type_ == "" {
		type_ = "file"
	}

	return uid, gid, mode, type_
}
开发者ID:akshaykarle,项目名称:lxd,代码行数:31,代码来源:util.go

示例13: CopyHeaders

// Utility function for copying HTTP Headers.
func CopyHeaders(src, dst http.Header) {
	for k, vv := range src {
		for _, v := range vv {
			dst.Add(k, v)
		}
	}
}
开发者ID:William-Wai,项目名称:shipyard-agent,代码行数:8,代码来源:utils.go

示例14: SignedInId

// SignedInId returns the id of signed in user.
func SignedInId(header http.Header, sess session.SessionStore) int64 {
	if !models.HasEngine {
		return 0
	}

	if setting.Service.EnableReverseProxyAuth {
		webAuthUser := header.Get(setting.ReverseProxyAuthUser)
		if len(webAuthUser) > 0 {
			u, err := models.GetUserByName(webAuthUser)
			if err != nil {
				if err != models.ErrUserNotExist {
					log.Error("auth.user.SignedInId(GetUserByName): %v", err)
				}
				return 0
			}
			return u.Id
		}
	}

	uid := sess.Get("userId")
	if uid == nil {
		return 0
	}
	if id, ok := uid.(int64); ok {
		if _, err := models.GetUserById(id); err != nil {
			if err != models.ErrUserNotExist {
				log.Error("auth.user.SignedInId(GetUserById): %v", err)
			}
			return 0
		}
		return id
	}
	return 0
}
开发者ID:JustStone,项目名称:gogs,代码行数:35,代码来源:user.go

示例15: assertHeaders

func assertHeaders(t *testing.T, resHeaders http.Header, reqHeaders map[string]string) {
	for name, value := range reqHeaders {
		if resHeaders.Get(name) != value {
			t.Errorf("Invalid header '%s', wanted '%s', got '%s'", name, value, resHeaders.Get(name))
		}
	}
}
开发者ID:noscripter,项目名称:go-ipfs,代码行数:7,代码来源:handler_test.go


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