func copyHeader(dst, src http.Header) { for key, entry := range src { for _, value := range entry { dst.Add(key, value) } } }
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 }
func copyHeader(dst, src http.Header) { for k, vv := range src { for _, v := range vv { dst.Add(k, v) } } }
// 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") } }
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) }
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) } }
// 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) } } }
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 }
// 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) } } } } }
//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 }
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.") } }
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) } }
func mergeHeaders(dest http.Header, toAdd http.Header) { for key, values := range toAdd { for _, value := range values { dest.Add(key, value) } } }
func (c *ParseAPIClient) appendCommonHeaders(header http.Header) http.Header { if header == nil { header = make(http.Header) } header.Add("User-Agent", userAgent) return header }
func (self *Container) Run(command string, c chan Exec) { endpoint := "container/" + self.Uuid + "/exec/?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 } }
func copyHeader(in http.Header, out http.Header) { for k, vs := range in { for _, v := range vs { out.Add(k, v) } } }
func (self *Container) Logs(c chan Logs) { endpoint := "container/" + self.Uuid + "/logs/?user="******"&token=" + ApiKey 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 Logs for { if err = ws.ReadJSON(&msg); err != nil { if err != nil && err.Error() != "EOF" { log.Println(err) } else { break } } c <- msg } }
// UpdateHeaders appends the contents of newHeaders to headers. func UpdateHeaders(headers *http.Header, newHeaders *http.Header) { for key, values := range *newHeaders { for _, value := range values { headers.Add(key, value) } } }
func (cs *clientSuite) TestParseError(c *check.C) { resp := &http.Response{ Status: "404 Not Found", } err := client.ParseErrorInTest(resp) c.Check(err, check.ErrorMatches, `server error: "404 Not Found"`) h := http.Header{} h.Add("Content-Type", "application/json") resp = &http.Response{ Status: "400 Bad Request", Header: h, Body: ioutil.NopCloser(strings.NewReader(`{ "status-code": 400, "type": "error", "result": { "message": "invalid" } }`)), } err = client.ParseErrorInTest(resp) c.Check(err, check.ErrorMatches, "invalid") resp = &http.Response{ Status: "400 Bad Request", Header: h, Body: ioutil.NopCloser(strings.NewReader("{}")), } err = client.ParseErrorInTest(resp) c.Check(err, check.ErrorMatches, `server error: "400 Bad Request"`) }
// convert cocaine.Headers([][2]string) to http.Header(map[string][]string) func CocaineHeaderToHttpHeader(hdr Headers) http.Header { header := http.Header{} for _, hdrValues := range hdr { header.Add(hdrValues[0], hdrValues[1]) } return header }
func copyHeader(source http.Header, dest *http.Header) { for n, v := range source { for _, vv := range v { dest.Add(n, vv) } } }
func copyHeader(src map[string]*Values, dst http.Header) { for key, it := range src { for _, val := range it.Arr { dst.Add(key, val) } } }
// Retrieve the list of bytes already transferred by an unfinished upload func (c *Client) GetUploadBytesSize(fileId, uploadId string, etags []string) (int, error) { route := strings.Join([]string{FILE_ROUTE, fileId, "content"}, "/") link := c.getURL(route, "") newHeader := http.Header{} newHeader.Set("Content-Range", "bytes /*/") newHeader.Set("Upload-ID", uploadId) newHeader.Set("Content-Length", "0") if len(etags) > 0 { for _, v := range etags { newHeader.Add("If-Match", v) } } res, err := c.request("PUT", link, &newHeader, nil) defer res.Body.Close() if err != nil { return 0, nil } bytesUploaded, err := strconv.Atoi(res.Header.Get("Range")) if err != nil { return 0, errors.New("Unable to parse value of bytes transferred from HTTP-Header") } return bytesUploaded, err }
func main() { conn, err := net.Dial("tcp", "localhost:8080") if err != nil { panic(err) } spdyConn, err := spdystream.NewConnection(conn, false) if err != nil { panic(err) } header := http.Header{} header.Add(":method", "GET") header.Add(":path", "/") go spdyConn.Serve(spdystream.NoOpStreamHandler) stream, err := spdyConn.CreateStream(header, nil, false) if err != nil { panic(err) } stream.Wait() fmt.Fprint(stream, "Writing to stream") buf := make([]byte, 25) stream.Read(buf) fmt.Println(string(buf)) stream.Close() }
func (self *HTTPClient) defaultRequest() (req *http.Request, err error) { var h http.Header = map[string][]string{} req = new(http.Request) req.Method = self.method if self.contentType != "" { headers := map[string]string{"Content-Type": self.contentType} for k, v := range headers { h.Add(k, v) } } //Request should have a Header, otherwise the //transport will not work. req.Header = h req.ProtoMajor = 1 req.ProtoMinor = 1 if self.cookie.Name != "" && self.cookie.Value != "" { req.AddCookie(&http.Cookie{Name: self.cookie.Name, Value: self.cookie.Value}) } if req.URL, err = url.Parse(self.addr); err != nil { return } return }
func (s *Server) handleRoom(w http.ResponseWriter, r *http.Request) { ctx := s.rootCtx.Fork() // Resolve the room. // TODO: support room creation? roomName := mux.Vars(r)["room"] room, err := s.b.GetRoom(ctx, roomName) if err != nil { if err == proto.ErrRoomNotFound { http.Error(w, "404 page not found", http.StatusNotFound) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } // Tag the agent. We use an authenticated but un-encrypted cookie. agent, cookie, agentKey, err := getAgent(ctx, s, r) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } client := &proto.Client{Agent: agent} client.FromRequest(ctx, r) // Look up account associated with agent. var accountID snowflake.Snowflake if err := accountID.FromString(agent.AccountID); agent.AccountID != "" && err == nil { if err := client.AuthenticateWithAgent(ctx, s.b, room, agent, agentKey); err != nil { fmt.Printf("agent auth failed: %s\n", err) switch err { case proto.ErrAccessDenied: http.Error(w, err.Error(), http.StatusForbidden) default: http.Error(w, err.Error(), http.StatusInternalServerError) } return } } // Upgrade to a websocket and set cookie. headers := http.Header{} if cookie != nil { headers.Add("Set-Cookie", cookie.String()) } conn, err := upgrader.Upgrade(w, r, headers) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer conn.Close() // Serve the session. session := newSession(ctx, s, conn, roomName, room, client, agentKey) if err = session.serve(); err != nil { // TODO: error handling return } }
func copyHeaders(dst, src http.Header) { for k, vs := range src { for _, v := range vs { dst.Add(k, v) } } }
func getHeaders(route *plugins.AppPluginRoute, orgId int64, appId string) (http.Header, error) { result := http.Header{} query := m.GetAppSettingByAppIdQuery{OrgId: orgId, AppId: appId} if err := bus.Dispatch(&query); err != nil { return nil, err } data := templateData{ JsonData: query.Result.JsonData, SecureJsonData: query.Result.SecureJsonData.Decrypt(), } for _, header := range route.Headers { var contentBuf bytes.Buffer t, err := template.New("content").Parse(header.Content) if err != nil { return nil, errors.New(fmt.Sprintf("could not parse header content template for header %s.", header.Name)) } err = t.Execute(&contentBuf, data) if err != nil { return nil, errors.New(fmt.Sprintf("failed to execute header content template for header %s.", header.Name)) } log.Trace("Adding header to proxy request. %s: %s", header.Name, contentBuf.String()) result.Add(header.Name, contentBuf.String()) } return result, nil }
func TestAuthChallengeParse(t *testing.T) { header := http.Header{} header.Add("WWW-Authenticate", `Bearer realm="https://auth.example.com/token",service="registry.example.com",other=fun,slashed="he\"\l\lo"`) challenges := parseAuthHeader(header) if len(challenges) != 1 { t.Fatalf("Unexpected number of auth challenges: %d, expected 1", len(challenges)) } challenge := challenges[0] if expected := "bearer"; challenge.Scheme != expected { t.Fatalf("Unexpected scheme: %s, expected: %s", challenge.Scheme, expected) } if expected := "https://auth.example.com/token"; challenge.Parameters["realm"] != expected { t.Fatalf("Unexpected param: %s, expected: %s", challenge.Parameters["realm"], expected) } if expected := "registry.example.com"; challenge.Parameters["service"] != expected { t.Fatalf("Unexpected param: %s, expected: %s", challenge.Parameters["service"], expected) } if expected := "fun"; challenge.Parameters["other"] != expected { t.Fatalf("Unexpected param: %s, expected: %s", challenge.Parameters["other"], expected) } if expected := "he\"llo"; challenge.Parameters["slashed"] != expected { t.Fatalf("Unexpected param: %s, expected: %s", challenge.Parameters["slashed"], expected) } }
// createProfile receives a hash and an optional username. // If there is a username, it must be unique. func createProfile(u *url.URL, h http.Header, r *Auth) (int, http.Header, Response, error) { var err error p := new(profile.Profile) a := profile.NewAuth(r.Hash, r.Username) // if Getting an Auth succeeds, there was an existing row err = a.Get() if err == nil { return error400("auth exists", "hash:", *r.Hash) } a.Name = r.Name err = p.Create() if err != nil { return error500("db failure: p56", err.Error()) } a.Profile = p.Id err = a.Create() if err != nil { return error500("db failure: p62", err.Error()) } // if all is well... oh := http.Header{} oh.Add(ChuteToken, *a.Token) response := Profile{Id: p.Id, Created: p.Created} return http.StatusCreated, oh, response, nil }