Golang CanonicalHeaderKey示例

说明

golang canonicalheaderkey示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net/http

示例#1
文件: gcm.go 项目: jiho2468/go-gcm

// httpGcmClient implementation to send a message through GCM Http server.
func (c *httpGcmClient) send(apiKey string, m HttpMessage) (*HttpResponse, error) {
	bs, err := json.Marshal(m)
	if err != nil {
		return nil, fmt.Errorf("error marshalling message>%v", err)
	}
	debug("sending", string(bs))
	req, err := http.NewRequest("POST", c.GcmURL, bytes.NewReader(bs))
	if err != nil {
		return nil, fmt.Errorf("error creating request>%v", err)
	}
	req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json")
	req.Header.Add(http.CanonicalHeaderKey("Authorization"), authHeader(apiKey))
	httpResp, err := c.HttpClient.Do(req)
	if err != nil {
		return nil, fmt.Errorf("error sending request to HTTP connection server>%v", err)
	}
	gcmResp := &HttpResponse{}
	body, err := ioutil.ReadAll(httpResp.Body)
	defer httpResp.Body.Close()
	if err != nil {
		return gcmResp, fmt.Errorf("error reading http response body>%v", err)
	}
	debug("received body", string(body))
	err = json.Unmarshal(body, &gcmResp)
	if err != nil {
		return gcmResp, fmt.Errorf("error unmarshaling json from body: %v", err)
	}
	// TODO(silvano): this is assuming that the header contains seconds instead of a date, need to check
	c.retryAfter = httpResp.Header.Get(http.CanonicalHeaderKey("Retry-After"))
	return gcmResp, nil
}

示例#2
文件: rawtrainrecord_test.go 项目: Lkyzlwj/Graduate

func auth(t interface{}) string {
	b, _ := json.Marshal(&mocked_auth_info)
	r, _ := http.NewRequest("POST", "/api/auth", bytes.NewBuffer(b))
	w := httptest.NewRecorder()
	beego.BeeApp.Handlers.ServeHTTP(w, r)

	beego.Trace("testing", "Test_PlayersController_Insert_Query_Update(Auth)", "Code[%d]\n%s", w.Code,
		w.Body.String())

	Convey("Subject: Test RawTrainRecord Endpoint\n", t, func() {
		Convey("Status code should be 200", func() {
			So(w.Code, ShouldEqual, 200)
		})
		Convey("The result should not be empty", func() {
			So(w.Body.Len(), ShouldBeGreaterThan, 0)
		})
		Convey("The result should be an true Success", func() {
			type Success struct {
				Succ bool `json:"success"`
			}
			var result Success
			json.Unmarshal(w.Body.Bytes(), &result)
			So(result == Success{true}, ShouldBeTrue)
		})
		Convey("The response should set session", func() {
			So(strings.Contains(w.HeaderMap.Get(
				http.CanonicalHeaderKey("Set-Cookie")), "beegosessionID"), ShouldBeTrue)
		})
	})
	return w.HeaderMap.Get(http.CanonicalHeaderKey("Set-Cookie"))
}

示例#3
文件: connection.go 项目: HackLinux/nimbus.io

// modifyHeaders tweaks the the headers for handoff to the internal server
func modifyHeaders(request *http.Request, remoteAddress, requestID string) {
	/*
		alan says this:

		still I don't feel great about this. from a security standpoint,
		signaling access control information (such as IP address, which some
		collections set access policy for) inside a stream of data controlled by
		the attacker is a bad idea.  downstream http parsers are probably robust
		enough to not be easily trickable, but I'd feel better about signaling
		out of band, or adding another header with a HMAC from a secret key.
	*/

	forwardedForKey := http.CanonicalHeaderKey("x-forwarded-for")
	existingForwardedFor := request.Header.Get(forwardedForKey)
	var newForwardedFor string
	if existingForwardedFor == "" {
		newForwardedFor = remoteAddress
	} else {
		newForwardedFor = fmt.Sprintf("%s, %s", existingForwardedFor,
			remoteAddress)
	}
	request.Header.Set(forwardedForKey, newForwardedFor)

	requestIDKey := http.CanonicalHeaderKey("x-nimbus-io-user-request-id")
	request.Header.Set(requestIDKey, requestID)
}

示例#4
文件: request.go 项目: hobbs/go-json-rest

// Derive CorsInfo from Request
func (self *Request) GetCorsInfo() *CorsInfo {

	origin := self.Header.Get("Origin")
	originUrl, err := url.ParseRequestURI(origin)

	isCors := err == nil && origin != "" && self.Host != originUrl.Host

	reqMethod := self.Header.Get("Access-Control-Request-Method")

	reqHeaders := []string{}
	rawReqHeaders := self.Header[http.CanonicalHeaderKey("Access-Control-Request-Headers")]
	for _, rawReqHeader := range rawReqHeaders {
		// net/http does not handle comma delimited headers for us
		for _, reqHeader := range strings.Split(rawReqHeader, ",") {
			reqHeaders = append(reqHeaders, http.CanonicalHeaderKey(strings.TrimSpace(reqHeader)))
		}
	}

	isPreflight := isCors && self.Method == "OPTIONS" && reqMethod != ""

	return &CorsInfo{
		IsCors:                      isCors,
		IsPreflight:                 isPreflight,
		Origin:                      origin,
		OriginUrl:                   originUrl,
		AccessControlRequestMethod:  reqMethod,
		AccessControlRequestHeaders: reqHeaders,
	}
}

示例#5
文件: v4.go 项目: advincze/wercker-ecs

func (v4 *signer) buildCanonicalHeaders() {
	var headers []string
	headers = append(headers, "host")
	for k := range v4.Request.Header {
		if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok {
			continue // ignored header
		}
		headers = append(headers, strings.ToLower(k))
	}
	sort.Strings(headers)

	v4.signedHeaders = strings.Join(headers, ";")

	if v4.isPresign {
		v4.Query.Set("X-Amz-SignedHeaders", v4.signedHeaders)
	}

	headerValues := make([]string, len(headers))
	for i, k := range headers {
		if k == "host" {
			headerValues[i] = "host:" + v4.Request.URL.Host
		} else {
			headerValues[i] = k + ":" +
				strings.Join(v4.Request.Header[http.CanonicalHeaderKey(k)], ",")
		}
	}

	v4.canonicalHeaders = strings.Join(headerValues, "\n")
}

示例#6
文件: async_test.go 项目: Azure/go-autorest

func TestDoPollForAsynchronous_ReturnsErrorForLastErrorResponse(t *testing.T) {
	// Return error code and message if error present in last response
	r1 := newAsynchronousResponse()
	r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
	r2 := newProvisioningStatusResponse("busy")
	r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
	r3 := newAsynchronousResponseWithError()
	r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))

	client := mocks.NewSender()
	client.AppendResponse(r1)
	client.AppendAndRepeatResponse(r2, 2)
	client.AppendAndRepeatResponse(r3, 1)

	r, err := autorest.SendWithSender(client, mocks.NewRequest(),
		DoPollForAsynchronous(time.Millisecond))

	expected := makeLongRunningOperationErrorString("InvalidParameter", "tom-service-DISCOVERY-server-base-v1.core.local' is not a valid captured VHD blob name prefix.")
	if err.Error() != expected {
		t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for an unknown error. \n expected=%q \n got=%q",
			expected, err.Error())
	}

	autorest.Respond(r,
		autorest.ByClosing())
}

示例#7
文件: async_test.go 项目: Azure/go-autorest

func TestDoPollForAsynchronous_ReturnsAnUnknownErrorForFailedOperations(t *testing.T) {
	// Return unknown error if error not present in last response
	r1 := newAsynchronousResponse()
	r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
	r2 := newProvisioningStatusResponse("busy")
	r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
	r3 := newProvisioningStatusResponse(operationFailed)
	r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))

	client := mocks.NewSender()
	client.AppendResponse(r1)
	client.AppendAndRepeatResponse(r2, 2)
	client.AppendAndRepeatResponse(r3, 1)

	r, err := autorest.SendWithSender(client, mocks.NewRequest(),
		DoPollForAsynchronous(time.Millisecond))

	expected := makeLongRunningOperationErrorString("Unknown", "None")
	if err.Error() != expected {
		t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for an unknown error. \n expected=%q \n got=%q",
			expected, err.Error())
	}

	autorest.Respond(r,
		autorest.ByClosing())
}

示例#8
文件: repository.go 项目: CodingDance/harbor

func (r *Repository) initiateBlobUpload(name string) (location, uploadUUID string, err error) {
	req, err := http.NewRequest("POST", buildInitiateBlobUploadURL(r.Endpoint.String(), r.Name), nil)
	req.Header.Set(http.CanonicalHeaderKey("Content-Length"), "0")

	resp, err := r.client.Do(req)
	if err != nil {
		ok, e := isUnauthorizedError(err)
		if ok {
			err = e
			return
		}
		return
	}

	if resp.StatusCode == http.StatusAccepted {
		location = resp.Header.Get(http.CanonicalHeaderKey("Location"))
		uploadUUID = resp.Header.Get(http.CanonicalHeaderKey("Docker-Upload-UUID"))
		return
	}

	defer resp.Body.Close()

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	err = errors.Error{
		StatusCode: resp.StatusCode,
		StatusText: resp.Status,
		Message:    string(b),
	}

	return
}

示例#9
文件: handler-utils.go 项目: balamurugana/minio

// extractMetadataFromHeader extracts metadata from HTTP header.
func extractMetadataFromHeader(header http.Header) map[string]string {
	metadata := make(map[string]string)
	// Save standard supported headers.
	for _, supportedHeader := range supportedHeaders {
		canonicalHeader := http.CanonicalHeaderKey(supportedHeader)
		// HTTP headers are case insensitive, look for both canonical
		// and non canonical entries.
		if _, ok := header[canonicalHeader]; ok {
			metadata[supportedHeader] = header.Get(canonicalHeader)
		} else if _, ok := header[supportedHeader]; ok {
			metadata[supportedHeader] = header.Get(supportedHeader)
		}
	}
	// Go through all other headers for any additional headers that needs to be saved.
	for key := range header {
		cKey := http.CanonicalHeaderKey(key)
		if strings.HasPrefix(cKey, "X-Amz-Meta-") {
			metadata[cKey] = header.Get(key)
		} else if strings.HasPrefix(key, "X-Minio-Meta-") {
			metadata[cKey] = header.Get(key)
		}
	}
	// Return.
	return metadata
}

示例#10
文件: httpConn.go 项目: Comcast/golang-money

// AddResponseMoneyToRW take the different money values between a http.Response and
// http.ResponseWriter and applies those different values from the http.Response to the
// http.ResponseWriter.
func AddResponseDiffToRW(rw http.ResponseWriter, resp *http.Response) http.ResponseWriter {
	var rwMNY []*Money
	for _, m := range rw.Header()[http.CanonicalHeaderKey(HEADER)] {
		rwMNY = append(rwMNY, StringToObject(m))
	}

	var respMNY []*Money
	for _, m := range resp.Header[http.CanonicalHeaderKey(HEADER)] {
		respMNY = append(respMNY, StringToObject(m))
	}

	for _, rp := range respMNY {
		found := false

		for _, rw := range rwMNY {
			if rw.spanId == rp.spanId {
				found = true
				break
			}
		}

		if !found {
			rw.Header().Add(HEADER, rp.ToString())
		}
	}

	return rw
}

示例#11
文件: repository.go 项目: vmware/harbor

// PushManifest ...
func (r *Repository) PushManifest(reference, mediaType string, payload []byte) (digest string, err error) {
	req, err := http.NewRequest("PUT", buildManifestURL(r.Endpoint.String(), r.Name, reference),
		bytes.NewReader(payload))
	if err != nil {
		return
	}
	req.Header.Set(http.CanonicalHeaderKey("Content-Type"), mediaType)

	resp, err := r.client.Do(req)
	if err != nil {
		err = parseError(err)
		return
	}

	defer resp.Body.Close()

	if resp.StatusCode == http.StatusCreated {
		digest = resp.Header.Get(http.CanonicalHeaderKey("Docker-Content-Digest"))
		return
	}

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	err = ®istry_error.Error{
		StatusCode: resp.StatusCode,
		Detail:     string(b),
	}

	return
}

示例#12
文件: repository.go 项目: vmware/harbor

func (r *Repository) initiateBlobUpload(name string) (location, uploadUUID string, err error) {
	req, err := http.NewRequest("POST", buildInitiateBlobUploadURL(r.Endpoint.String(), r.Name), nil)
	req.Header.Set(http.CanonicalHeaderKey("Content-Length"), "0")

	resp, err := r.client.Do(req)
	if err != nil {
		err = parseError(err)
		return
	}

	defer resp.Body.Close()

	if resp.StatusCode == http.StatusAccepted {
		location = resp.Header.Get(http.CanonicalHeaderKey("Location"))
		uploadUUID = resp.Header.Get(http.CanonicalHeaderKey("Docker-Upload-UUID"))
		return
	}

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	err = ®istry_error.Error{
		StatusCode: resp.StatusCode,
		Detail:     string(b),
	}

	return
}

示例#13
文件: header.go 项目: brunoqc/martian

// All returns all the values for header name. If the header does not exist it
// returns nil, false.
func (h *Header) All(name string) ([]string, bool) {
	switch http.CanonicalHeaderKey(name) {
	case "Host":
		if h.host() == "" {
			return nil, false
		}

		return []string{h.host()}, true
	case "Content-Length":
		if h.cl() <= 0 {
			return nil, false
		}

		return []string{strconv.FormatInt(h.cl(), 10)}, true
	case "Transfer-Encoding":
		if h.te() == nil {
			return nil, false
		}

		return h.te(), true
	default:
		vs, ok := h.h[http.CanonicalHeaderKey(name)]
		return vs, ok
	}
}

示例#14
文件: replication_job.go 项目: yaolingling/harbor

// GetLog ...
func (ra *RepJobAPI) GetLog() {
	if ra.jobID == 0 {
		ra.CustomAbort(http.StatusBadRequest, "id is nil")
	}

	resp, err := http.Get(buildJobLogURL(strconv.FormatInt(ra.jobID, 10)))
	if err != nil {
		log.Errorf("failed to get log for job %d: %v", ra.jobID, err)
		ra.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
	}

	if resp.StatusCode == http.StatusOK {
		ra.Ctx.ResponseWriter.Header().Set(http.CanonicalHeaderKey("Content-Length"), resp.Header.Get(http.CanonicalHeaderKey("Content-Length")))
		ra.Ctx.ResponseWriter.Header().Set(http.CanonicalHeaderKey("Content-Type"), "text/plain")

		if _, err = io.Copy(ra.Ctx.ResponseWriter, resp.Body); err != nil {
			log.Errorf("failed to write log to response; %v", err)
			ra.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
		}
		return
	}

	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Errorf("failed to read reponse body: %v", err)
		ra.CustomAbort(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
	}

	ra.CustomAbort(resp.StatusCode, string(b))
}

示例#15
文件: gcm_test.go 项目: jiho2468/go-gcm

// Test send for http client
func TestHttpClientSend(t *testing.T) {
	expectedRetryAfter := "10"
	var authHeader string
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set(http.CanonicalHeaderKey("Content-Type"), "application/json")
		w.Header().Set(http.CanonicalHeaderKey("Retry-After"), expectedRetryAfter)
		w.WriteHeader(200)
		fmt.Fprintln(w, expectedResp)
	}))
	defer server.Close()

	transport := &http.Transport{
		Proxy: func(req *http.Request) (*url.URL, error) {
			authHeader = req.Header.Get(http.CanonicalHeaderKey("Authorization"))
			return url.Parse(server.URL)
		},
	}
	httpClient := &http.Client{Transport: transport}
	c := &httpGcmClient{server.URL, httpClient, "0"}
	response, error := c.send("apiKey", *singleTargetMessage)
	expectedAuthHeader := "key=apiKey"
	expResp := &HttpResponse{}
	err := json.Unmarshal([]byte(expectedResp), &expResp)
	if err != nil {
		t.Fatalf("error: %v", err)
	}
	assertEqual(t, authHeader, expectedAuthHeader)
	assertEqual(t, error, nil)
	assertDeepEqual(t, response, expResp)
	assertEqual(t, c.getRetryAfter(), expectedRetryAfter)
}

示例#16
文件: request.go 项目: drichardson/appengine

// ParseHTTPRequest parses the SignedRequest from an http.Request
// created with HTTPRequest.
func ParseHTTPRequest(r *http.Request) (*SignedRequest, error) {

	signature := r.Header.Get("Signature")
	expirationStr := r.Header.Get("Signature-Expiration")
	signedHeaderKeys, _ := r.Header[http.CanonicalHeaderKey("Signed-Headers")]

	expiration, err := time.Parse(time.RFC3339, expirationStr)
	if err != nil {
		return nil, err
	}

	signedHeaders := make(http.Header)
	for _, key := range signedHeaderKeys {
		signedHeaders[key] = r.Header[http.CanonicalHeaderKey(key)]
	}

	p := &SignedRequest{
		Method:     r.Method,
		URL:        r.URL.String(),
		Expiration: expiration,
		Headers:    signedHeaders,
		Signature:  signature,
	}

	return p, nil
}

示例#17
文件: sign.go 项目: elblivion/s3gof3r

func (s *signer) buildCanonicalHeaders() {
	var headers []string
	headers = append(headers, "host")
	for k := range s.Request.Header {
		if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok {
			continue
		}
		headers = append(headers, strings.ToLower(k))
	}
	sort.Strings(headers)

	s.signedHeaders = strings.Join(headers, ";")

	headerValues := make([]string, len(headers))
	for i, k := range headers {
		if k == "host" {
			headerValues[i] = "host:" + s.Request.URL.Host
		} else {
			headerValues[i] = k + ":" +
				strings.Join(s.Request.Header[http.CanonicalHeaderKey(k)], ",")
		}
	}

	s.canonicalHeaders = strings.Join(headerValues, "\n")
}

示例#18
文件: httpcache_test.go 项目: Richardphp/noms

func containsHeader(headers []string, header string) bool {
	for _, v := range headers {
		if http.CanonicalHeaderKey(v) == http.CanonicalHeaderKey(header) {
			return true
		}
	}
	return false
}

示例#19
文件: async_test.go 项目: Azure/go-autorest

func newAsynchronousResponse() *http.Response {
	r := mocks.NewResponseWithStatus("201 Created", http.StatusCreated)
	r.Body = mocks.NewBody(fmt.Sprintf(pollingStateFormat, operationInProgress))
	mocks.SetResponseHeader(r, http.CanonicalHeaderKey(headerAsyncOperation), mocks.TestAzureAsyncURL)
	mocks.SetResponseHeader(r, http.CanonicalHeaderKey(autorest.HeaderLocation), mocks.TestLocationURL)
	mocks.SetRetryHeader(r, retryDelay)
	r.Request = mocks.NewRequestForURL(mocks.TestURL)
	return r
}

示例#20
文件: commands.go 项目: Masterminds/cookoo

// Flush sends content to output.
//
// If no writer is specified, this will attempt to write to whatever is in the
// Context with the key "http.ResponseWriter". If no suitable writer is found, it will
// not write to anything at all.
//
// Params:
// 	- writer: A Writer of some sort. This will try to write to the HTTP response if no writer
// 	is specified.
// 	- content: The content to write as a body. If this is a byte[], it is sent unchanged. Otherwise.
// 	we first try to convert to a string, then pass it into a writer.
// 	- contentType: The content type header (e.g. text/html). Default is text/plain
// 	- responseCode: Integer HTTP Response Code: Default is `http.StatusOK`.
// 	- headers: a map[string]string of HTTP headers. The keys will be run through
// 	 http.CannonicalHeaderKey()
//
// Note that this is optimized for writing from strings or arrays, not Readers. For larger
// objects, you may find it more efficient to use a different command.
//
// Context:
// - If this finds `web.ContentEncoding`, it will set a content-encoding header.
//
// Returns
//
// 	- boolean true
func Flush(cxt cookoo.Context, params *cookoo.Params) (interface{}, cookoo.Interrupt) {

	// Make sure we have a place to write this stuff.
	writer, ok := params.Has("writer")
	if writer == nil {
		writer, ok = cxt.Has("http.ResponseWriter")
		if !ok {
			return false, nil
		}
	}
	out := writer.(http.ResponseWriter)

	// Get the rest of the info.
	code := params.Get("responseCode", http.StatusOK).(int)
	header := out.Header()
	contentType := params.Get("contentType", "text/plain; charset=utf-8").(string)

	// Prepare the content.
	var content []byte
	rawContent, ok := params.Has("content")
	if !ok {
		// No content. Send nothing in the body.
		content = []byte("")
	} else if byteContent, ok := rawContent.([]byte); ok {
		// Got a byte[]; add it as is.
		content = byteContent
	} else {
		// Use the formatter to convert to a string, and then
		// cast it to bytes.
		content = []byte(fmt.Sprintf("%v", rawContent))
	}

	// Add headers:
	header.Set(http.CanonicalHeaderKey("content-type"), contentType)

	te := cxt.Get(ContentEncoding, "").(string)
	if len(te) > 0 {
		header.Set(http.CanonicalHeaderKey("transfer-encoding"), te)
	}

	headerO, ok := params.Has("headers")
	if ok {
		headers := headerO.(map[string]string)
		for k, v := range headers {
			header.Add(http.CanonicalHeaderKey(k), v)
		}
	}

	// Send the headers.
	out.WriteHeader(code)

	//io.WriteString(out, content)
	out.Write(content)

	return true, nil
}

示例#21
文件: autorest_test.go 项目: oaastest/go-autorest

func TestCreatePollingRequestAppliesAuthorization(t *testing.T) {
	resp := mocks.NewResponseWithStatus("202 Accepted", 202)
	addAcceptedHeaders(resp)

	req, _ := CreatePollingRequest(resp, TestAuthorizer{})
	if req.Header.Get(http.CanonicalHeaderKey(headerAuthorization)) != testAuthorizationHeader {
		t.Errorf("autorest: CreatePollingRequest did not apply authorization -- received %v, expected %v",
			req.Header.Get(http.CanonicalHeaderKey(headerAuthorization)), testAuthorizationHeader)
	}
}

示例#22
文件: client_test.go 项目: kbxkb/azure-sdk-for-go

func TestClientSendSetsAuthorization(t *testing.T) {
	r := mocks.NewRequest()
	s := mocks.NewSender()
	c := Client{Authorizer: mockAuthorizer{}, Sender: s}

	c.Send(r)
	if len(r.Header.Get(http.CanonicalHeaderKey(headerAuthorization))) <= 0 {
		t.Errorf("autorest: Client#Send failed to set Authorization header -- %s=%s",
			http.CanonicalHeaderKey(headerAuthorization),
			r.Header.Get(http.CanonicalHeaderKey(headerAuthorization)))
	}
}

示例#23
文件: client_test.go 项目: kbxkb/azure-sdk-for-go

func TestClientDoSetsUserAgent(t *testing.T) {
	c := Client{UserAgent: "UserAgent"}
	r := mocks.NewRequest()

	c.Do(r)

	if r.Header.Get(http.CanonicalHeaderKey(headerUserAgent)) != "UserAgent" {
		t.Errorf("autorest: Client#Do failed to correctly set User-Agent header: %s=%s",
			http.CanonicalHeaderKey(headerUserAgent),
			r.Header.Get(http.CanonicalHeaderKey(headerUserAgent)))
	}
}

示例#24
文件: async_test.go 项目: Azure/go-autorest

func TestUpdatePollingState_ReturnsAnErrorIfAsyncHeadersAreMissingForANewOrDeletedObject(t *testing.T) {
	resp := newAsynchronousResponse()
	resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
	resp.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation))

	for _, m := range []string{methodDelete, methodPost} {
		resp.Request.Method = m
		err := updatePollingState(resp, &pollingState{})
		if err == nil {
			t.Fatalf("azure: updatePollingState failed to return an error even though it could not determine the polling URL for Method '%s'", m)
		}
	}
}

示例#25
文件: clever.go 项目: Clever/clever-go

// TooManyRequestsError creates a TooManyRequestsError
func (err *TooManyRequestsError) Error() string {
	errString := "Too Many Requests"
	for bucketIndex, bucketName := range err.Header[http.CanonicalHeaderKey("X-Ratelimit-Bucket")] {
		errString += fmt.Sprintf("\nBucket: %s", bucketName)
		for _, prop := range []string{"Remaining", "Limit", "Reset"} {
			headersForProp := err.Header[http.CanonicalHeaderKey("X-Ratelimit-"+prop)]
			if bucketIndex < len(headersForProp) {
				errString += fmt.Sprintf(", %s: %s", prop, headersForProp[bucketIndex])
			}
		}
	}
	return errString
}

示例#26
文件: async_test.go 项目: Azure/go-autorest

func TestUpdatePollingState_UsesTheObjectLocationIfAsyncHeadersAreMissing(t *testing.T) {
	resp := newAsynchronousResponse()
	resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
	resp.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation))
	resp.Request.Method = methodPatch

	ps := pollingState{}
	updatePollingState(resp, &ps)

	if ps.uri != mocks.TestURL {
		t.Fatal("azure: updatePollingState failed to use the Object URL when the asynchronous headers are missing")
	}
}

示例#27
文件: login.go 项目: Zxnui/go_web_demo

//保存登录数据
func LoginPost(w http.ResponseWriter, r *http.Request) {
	submit := r.PostFormValue("submit")
	if strings.EqualFold(submit, "1") {
		http.Redirect(w, r, "/loginInfo", http.StatusFound)
		return
	}
	data := make(map[string]string)
	login, err := template.ParseFiles("views/login.html", "views/common/head.tpl")
	if pageNotFound(w, err) {
		return
	}

	uname := r.PostFormValue("uname")
	pwd := r.PostFormValue("pwd")
	checkbox := r.PostFormValue("autoLogin") == "on"

	user, has, err := models.GetUserInfo(uname)
	_ = CheckError("查询用户失败:", err)

	if has {
		if strings.EqualFold(user.Passwd, GetMd5String(pwd)) {
			if checkbox {
				newCookie := http.Cookie{
					Name:   http.CanonicalHeaderKey("uname"),
					Value:  uname,
					MaxAge: 1<<31 - 1,
				}
				http.SetCookie(w, &newCookie)
			} else {
				newCookie := http.Cookie{
					Name:   http.CanonicalHeaderKey("uname"),
					Value:  uname,
					MaxAge: 0,
				}
				http.SetCookie(w, &newCookie)
			}
			http.Redirect(w, r, "/", http.StatusFound)
			return
		} else {
			data["error"] = "密码错误"
			data["uname"] = uname
			login.Execute(w, data)
			return
		}
	} else {
		data["error"] = "用户不存在"
		login.Execute(w, data)
		return
	}
}

示例#28
文件: info.go 项目: tgulacsi/aostor

// returns the value for key
func (info *Info) Get(key string) string {
	ret, ok := info.m[http.CanonicalHeaderKey(key)]
	if !ok {
		for k := range info.m {
			k2 := http.CanonicalHeaderKey(k)
			if k != k2 {
				info.m[k2] = info.m[k]
				delete(info.m, k)
			}
		}
		ret = info.m[http.CanonicalHeaderKey(key)]
	}
	return ret
}

示例#29
文件: generic-handlers.go 项目: alexex/minio

// Parse date string from incoming header, current supports and verifies
// follow HTTP headers.
//
//  - X-Amz-Date
//  - X-Minio-Date
//  - Date
//
// In following time layouts ``time.RFC1123``, ``time.RFC1123Z`` and ``iso8601Format``.
func parseDateHeader(req *http.Request) (time.Time, error) {
	amzDate := req.Header.Get(http.CanonicalHeaderKey("x-amz-date"))
	if amzDate != "" {
		return parseKnownLayouts(amzDate)
	}
	minioDate := req.Header.Get(http.CanonicalHeaderKey("x-minio-date"))
	if minioDate != "" {
		return parseKnownLayouts(minioDate)
	}
	genericDate := req.Header.Get("Date")
	if genericDate != "" {
		return parseKnownLayouts(genericDate)
	}
	return time.Time{}, errors.New("Date header missing, invalid request.")
}

示例#30
文件: quay.go 项目: weaveworks/flux

func (t *wwwAuthenticateFixer) RoundTrip(req *http.Request) (*http.Response, error) {
	t.maybeAddToken(req)
	res, err := t.transport.RoundTrip(req)
	if err == nil {
		newAuthHeaders := []string{}
		for _, h := range res.Header[http.CanonicalHeaderKey("WWW-Authenticate")] {
			if strings.HasPrefix(h, "Bearer ") {
				h = replaceUnquoted(h)
			}
			newAuthHeaders = append(newAuthHeaders, h)
		}
		res.Header[http.CanonicalHeaderKey("WWW-Authenticate")] = newAuthHeaders
	}
	return res, err
}

展开阅读全文