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)
	}
}
Example #2
0
File: json.go Project: devick/flynn
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
}
Example #3
0
// 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
}
Example #4
0
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
}
Example #5
0
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

}
Example #6
0
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)
	}
}
Example #7
0
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
}
Example #8
0
func intHeader(key string, h http.Header) (int, error) {
	if header := h.Get(key); header != "" {
		return strconv.Atoi(header)
	} else {
		return 0, errNoHeader
	}
}
Example #9
0
func copyHeader(source http.Header, dest *http.Header) {
	for n, v := range source {
		for _, vv := range v {
			dest.Add(n, vv)
		}
	}
}
Example #10
0
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
}
Example #11
0
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
	}
}
Example #12
0
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_
}
Example #13
0
// 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)
		}
	}
}
Example #14
0
// 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
}
Example #15
0
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))
		}
	}
}
Example #16
0
// sandstormPermissions extracts the permissions in the request header.
func sandstormPermissions(h http.Header) []string {
	p := h.Get("X-Sandstorm-Permissions")
	if p == "" {
		return nil
	}
	return strings.Split(p, ",")
}
Example #17
0
func testGet(path string, headers map[string]string) *testResponse {
	var header http.Header
	for k, v := range headers {
		header.Set(k, v)
	}
	return getTestResponse("GET", path, "", header, nil)
}
Example #18
0
// 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")
	}
}
Example #19
0
func quakeV2(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result {
	if res := weft.CheckQuery(r, []string{}, []string{}); !res.Ok {
		return res
	}

	if len(r.URL.Query()) != 0 {
		return weft.BadRequest("incorrect number of query parameters.")
	}

	var publicID string
	var res *weft.Result

	if publicID, res = getPublicIDPath(r); !res.Ok {
		return res
	}

	var d string
	err := db.QueryRow(quakeV2SQL, publicID).Scan(&d)
	if err != nil {
		return weft.ServiceUnavailableError(err)
	}

	b.WriteString(d)
	h.Set("Content-Type", V2GeoJSON)
	return &weft.StatusOK
}
Example #20
0
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: Do not store reference
	s.streamC.L.Lock()
	s.streams[referenceID] = newStream
	s.streamC.L.Unlock()

	return newStream, nil

}
Example #21
0
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

}
Example #22
0
func (s *S) TestRespMustRevalidate(c *C) {
	respHeaders := http.Header{}
	respHeaders.Set("Cache-Control", "must-revalidate")
	reqHeaders := http.Header{}

	c.Assert(getFreshness(respHeaders, reqHeaders), Equals, stale)
}
Example #23
0
func (c *Context) newHTTPResponse(reqURL string, respURL string, body []byte, statusCode int, headers http.Header) otto.Value {
	respHeaders := make(map[string]string, len(headers))
	for k := range headers {
		respHeaders[k] = headers.Get(k)
	}
	return c.mustCallValue("new M.http.Response", nil, respURL, string(body), statusCode, reqURL, respHeaders).val
}
Example #24
0
func isVerifiedRequest(header http.Header, body []byte) bool {
	serverSignature := os.Getenv("SECRET")
	requestSignature := header.Get("X-Hub-Signature")

	// when not set up with a secret
	if len(serverSignature) < 1 {
		log.Println("http.request.signature.verification.skipped")
		return true
	}

	log.Println("http.request.signature.verification.started")

	if len(requestSignature) < 1 {
		log.Println("http.request.signature.verification.failed", "missing X-Hub-Signature header")
		return false
	}

	mac := hmac.New(sha1.New, []byte(serverSignature))
	mac.Write(body)
	expectedMAC := mac.Sum(nil)
	expectedSignature := "sha1=" + hex.EncodeToString(expectedMAC)
	signatureMatched := hmac.Equal([]byte(expectedSignature), []byte(requestSignature))

	if signatureMatched {
		log.Println("http.request.signature.verification.passed")
	} else {
		log.Println("http.request.signature.verification.failed")
	}

	return signatureMatched
}
Example #25
0
func copyHeaders(dst, src http.Header) {
	for k, vs := range src {
		for _, v := range vs {
			dst.Add(k, v)
		}
	}
}
Example #26
0
// ParseValueAndParams parses a comma separated list of values with optional
// semicolon separated name-value pairs. Content-Type and Content-Disposition
// headers are in this format.
func ParseValueAndParams(header http.Header, key string) (value string, params map[string]string) {
	params = make(map[string]string)
	s := header.Get(key)
	value, s = expectTokenSlash(s)
	if value == "" {
		return
	}
	value = strings.ToLower(value)
	s = skipSpace(s)
	for strings.HasPrefix(s, ";") {
		var pkey string
		pkey, s = expectToken(skipSpace(s[1:]))
		if pkey == "" {
			return
		}
		if !strings.HasPrefix(s, "=") {
			return
		}
		var pvalue string
		pvalue, s = expectTokenOrQuoted(s[1:])
		if pvalue == "" {
			return
		}
		pkey = strings.ToLower(pkey)
		params[pkey] = pvalue
		s = skipSpace(s)
	}
	return
}
Example #27
0
File: main.go Project: rsc/devweb
func copyHeader(dst, src http.Header) {
	for k, vv := range src {
		for _, v := range vv {
			dst.Add(k, v)
		}
	}
}
Example #28
0
func checkHeaderValue(h http.Header, key, expected string) error {
	actual := h.Get(key)
	if actual != expected {
		return fmt.Errorf("Unexpected header value for %q: %q, expected %q", key, actual, expected)
	}
	return nil
}
Example #29
0
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)
	}

}
Example #30
0
func fakeClientWith(testName string, t *testing.T, data map[string]string) ClientMapper {
	return ClientMapperFunc(func(*meta.RESTMapping) (RESTClient, error) {
		return &fake.RESTClient{
			Codec: testapi.Default.Codec(),
			Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
				p := req.URL.Path
				q := req.URL.RawQuery
				if len(q) != 0 {
					p = p + "?" + q
				}
				body, ok := data[p]
				if !ok {
					t.Fatalf("%s: unexpected request: %s (%s)\n%#v", testName, p, req.URL, req)
				}
				header := http.Header{}
				header.Set("Content-Type", runtime.ContentTypeJSON)
				return &http.Response{
					StatusCode: http.StatusOK,
					Header:     header,
					Body:       stringBody(body),
				}, nil
			}),
		}, nil
	})
}