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


Golang Header.Add方法代码示例

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


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

示例1: copyHeader

func copyHeader(dst, src http.Header) {
	for key, entry := range src {
		for _, value := range entry {
			dst.Add(key, value)
		}
	}
}
开发者ID:robertkrimen,项目名称:pianobarproxy,代码行数:7,代码来源:main.go

示例2: 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

示例3: copyHeader

func copyHeader(dst, src http.Header) {
	for k, vv := range src {
		for _, v := range vv {
			dst.Add(k, v)
		}
	}
}
开发者ID:rsc,项目名称:devweb,代码行数:7,代码来源:main.go

示例4: TestStreamReaderStopOnDial

// TestStreamReaderStopOnDial tests a stream reader closes the connection on stop.
func TestStreamReaderStopOnDial(t *testing.T) {
	defer testutil.AfterTest(t)
	h := http.Header{}
	h.Add("X-Server-Version", version.Version)
	tr := &respWaitRoundTripper{rrt: &respRoundTripper{code: http.StatusOK, header: h}}
	sr := &streamReader{
		peerID: types.ID(2),
		tr:     &Transport{streamRt: tr, ClusterID: types.ID(1)},
		picker: mustNewURLPicker(t, []string{"http://localhost:2380"}),
		errorc: make(chan error, 1),
		typ:    streamTypeMessage,
		status: newPeerStatus(types.ID(2)),
	}
	tr.onResp = func() {
		// stop() waits for the run() goroutine to exit, but that exit
		// needs a response from RoundTrip() first; use goroutine
		go sr.stop()
		// wait so that stop() is blocked on run() exiting
		time.Sleep(10 * time.Millisecond)
		// sr.run() completes dialing then begins decoding while stopped
	}
	sr.start()
	select {
	case <-sr.done:
	case <-time.After(time.Second):
		t.Fatal("streamReader did not stop in time")
	}
}
开发者ID:ringtail,项目名称:etcd,代码行数:29,代码来源:stream_test.go

示例5: GetFileContent

func (c *Client) GetFileContent(fileId, rangeEtag string, startIndex, endIndex int, matchEtags []string) ([]byte, *http.Header, error) {
	route := strings.Join([]string{FILE_ROUTE, fileId, "content"}, "/")
	link := c.getURL(route, "")

	// Construct header
	byteRange := fmt.Sprintf("bytes=%d-%d", startIndex, endIndex)
	newHeader := http.Header{}
	newHeader.Add("Range", byteRange)

	if rangeEtag != "" {
		newHeader.Set("If-Range", rangeEtag)
	}

	if len(matchEtags) > 0 {
		for _, v := range matchEtags {
			newHeader.Add("If-None-Match", v)
		}
	}

	res, err := c.request("GET", link, &newHeader, nil)
	if err != nil {
		return nil, nil, err
	}

	return unpackageResponse(res)
}
开发者ID:aerofs,项目名称:aerofs-sdk-golang,代码行数:26,代码来源:file.go

示例6: TestParseHeader_multiple

func TestParseHeader_multiple(t *testing.T) {
	h := http.Header{}
	h.Add("Link", `<https://example.com/?page=2>; rel="next",<https://example.com/?page=34>; rel="last"`)

	g := ParseHeader(h)

	if got, want := len(g), 2; got != want {
		t.Fatalf(`len(g) = %d, want %d`, got, want)
	}

	if g["next"] == nil {
		t.Fatalf(`g["next"] == nil`)
	}

	if got, want := g["next"].URI, "https://example.com/?page=2"; got != want {
		t.Fatalf(`g["next"].URI = %q, want %q`, got, want)
	}

	if got, want := g["next"].Rel, "next"; got != want {
		t.Fatalf(`g["next"].Rel = %q, want %q`, got, want)
	}

	if g["last"] == nil {
		t.Fatalf(`g["last"] == nil`)
	}

	if got, want := g["last"].URI, "https://example.com/?page=34"; got != want {
		t.Fatalf(`g["last"].URI = %q, want %q`, got, want)
	}

	if got, want := g["last"].Rel, "last"; got != want {
		t.Fatalf(`g["last"].Rel = %q, want %q`, got, want)
	}
}
开发者ID:peterhellberg,项目名称:link,代码行数:34,代码来源:link_test.go

示例7: 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

示例8: subscribeToEvents

func (router *EventRouter) subscribeToEvents(subscribeURL string, accessKey string, secretKey string, data url.Values) (*websocket.Conn, error) {
	dialer := &websocket.Dialer{}
	headers := http.Header{}
	headers.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(accessKey+":"+secretKey)))
	subscribeURL = subscribeURL + "?" + data.Encode()
	ws, resp, err := dialer.Dial(subscribeURL, headers)

	if err != nil {
		log.WithFields(log.Fields{
			"subscribeUrl": subscribeURL,
		}).Errorf("Error subscribing to events: %s", err)
		if resp != nil {
			log.WithFields(log.Fields{
				"status":          resp.Status,
				"statusCode":      resp.StatusCode,
				"responseHeaders": resp.Header,
			}).Error("Got error response")
			if resp.Body != nil {
				defer resp.Body.Close()
				body, _ := ioutil.ReadAll(resp.Body)
				log.Errorf("Error response: %s", body)
			}
		}
		return nil, err
	}
	return ws, nil
}
开发者ID:vdemeester,项目名称:rancher-compose,代码行数:27,代码来源:listener.go

示例9: copyHeadersForForwarding

// copyHeadersForForwarding will copy the headers but filter those that shouldn't be
// forwarded
func copyHeadersForForwarding(dst, src http.Header) {
	var extraHopByHopHeaders []string
	for k, vv := range src {
		switch k {
		// Skip hop-by-hop headers, ref section 13.5.1 of http://www.ietf.org/rfc/rfc2616.txt
		case "Connection":
			// section 14.10 of rfc2616
			// the slice is short typically, don't bother sort it to speed up lookup
			extraHopByHopHeaders = vv
		case "Keep-Alive":
		case "Proxy-Authenticate":
		case "Proxy-Authorization":
		case "TE":
		case "Trailers":
		case "Transfer-Encoding":
		case "Upgrade":
		default:
			if !contains(k, extraHopByHopHeaders) {
				for _, v := range vv {
					dst.Add(k, v)
				}
			}
		}
	}
}
开发者ID:journeyqiao,项目名称:http-proxy,代码行数:27,代码来源:utils.go

示例10: AllowCORS

//This is an implementation of HandleCORS function to allow all cross domain request.
func AllowCORS(r *http.Request, responseHeader http.Header) bool {
	responseHeader.Add("Access-Control-Allow-Origin", "*")
	if r.Method == "OPTIONS" {
		return false
	}
	return true
}
开发者ID:jakeo,项目名称:jas,代码行数:8,代码来源:router.go

示例11: TestBackendGoesAway

func TestBackendGoesAway(t *testing.T) {
	dialer := &websocket.Dialer{}
	headers := http.Header{}
	headers.Add("X-Cattle-HostId", "1")
	backendWs, _, err := dialer.Dial("ws://127.0.0.1:2222/connectbackend", headers)
	if err != nil {
		t.Fatal("Failed to connect to proxy.", err)
	}

	handlers := make(map[string]Handler)
	handlers["/v1/echo"] = &echoHandler{}
	go connectToProxyWS(backendWs, handlers)

	signedToken := test_utils.CreateToken("1", privateKey)
	url := "ws://localhost:2222/v1/echo?token=" + signedToken
	ws := getClientConnection(url, t)

	if err := ws.WriteMessage(1, []byte("a message")); err != nil {
		t.Fatal(err)
	}

	backendWs.Close()

	if _, _, err := ws.ReadMessage(); err != io.EOF {
		t.Fatal("Expected error indicating websocket was closed.")
	}

	dialer = &websocket.Dialer{}
	ws, _, err = dialer.Dial(url, http.Header{})
	if ws != nil || err != websocket.ErrBadHandshake {
		t.Fatal("Should not have been able to connect.")
	}

}
开发者ID:dx9,项目名称:host-api,代码行数:34,代码来源:backend_test.go

示例12: proxyDo

func proxyDo(method string, p *ProxyConfig, h http.Header) (io.ReadCloser, int, error) {
	req, err := http.NewRequest(method, p.Url, nil)
	if err != nil {
		return nil, 400, logex.Trace(err)
	}
	if p.Start >= 0 {
		setRange(req.Header, p.Start, p.End)
	}
	resp, err := DefaultClient.Do(req)
	if err != nil {
		return nil, 400, logex.Trace(err)
	}

	resp.Header.Set(H_SOURCE, resp.Request.URL.String())
	for k, v := range resp.Header {
		for _, vv := range v {
			h.Add(k, vv)
		}
	}

	switch resp.StatusCode {
	case 206:
		return resp.Body, resp.StatusCode, nil
	case 200:
		// panic
		return resp.Body, resp.StatusCode, nil
	default:
		return nil, resp.StatusCode, logex.NewError("remote error:", resp.Status)
	}
}
开发者ID:chzyer,项目名称:godl,代码行数:30,代码来源:proxy.go

示例13: mergeHeaders

func mergeHeaders(dest http.Header, toAdd http.Header) {
	for key, values := range toAdd {
		for _, value := range values {
			dest.Add(key, value)
		}
	}
}
开发者ID:pombredanne,项目名称:atomic-enterprise,代码行数:7,代码来源:default_auth_handler.go

示例14: appendCommonHeaders

func (c *ParseAPIClient) appendCommonHeaders(header http.Header) http.Header {
	if header == nil {
		header = make(http.Header)
	}
	header.Add("User-Agent", userAgent)
	return header
}
开发者ID:Georotzen,项目名称:parse-cli,代码行数:7,代码来源:client.go

示例15: Run

func (self *Container) Run(command string, c chan Exec) {

	endpoint := "container/" + self.Uuid + "/exec/?user=" + User + "&token=" + ApiKey + "&command=" + url.QueryEscape(command)
	url := StreamUrl + endpoint

	header := http.Header{}
	header.Add("User-Agent", customUserAgent)

	var Dialer websocket.Dialer
	ws, _, err := Dialer.Dial(url, header)
	if err != nil {
		log.Println(err)
	}

	var msg Exec
	for {
		if err = ws.ReadJSON(&msg); err != nil {
			if err != nil && err.Error() != "EOF" {
				log.Println(err)
			} else {
				break
			}
		}
		c <- msg
	}
}
开发者ID:Karm,项目名称:go-tutum,代码行数:26,代码来源:container.go


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