本文整理汇总了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)
}
}
}
示例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
}
示例3: copyHeader
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
示例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")
}
}
示例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)
}
示例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)
}
}
示例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)
}
}
}
示例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
}
示例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)
}
}
}
}
}
示例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
}
示例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.")
}
}
示例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)
}
}
示例13: mergeHeaders
func mergeHeaders(dest http.Header, toAdd http.Header) {
for key, values := range toAdd {
for _, value := range values {
dest.Add(key, value)
}
}
}
示例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
}
示例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
}
}