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


Golang http.CanonicalHeaderKey函数代码示例

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


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

示例1: send

// 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
}
开发者ID:jiho2468,项目名称:go-gcm,代码行数:32,代码来源:gcm.go

示例2: auth

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"))
}
开发者ID:Lkyzlwj,项目名称:Graduate,代码行数:31,代码来源:rawtrainrecord_test.go

示例3: modifyHeaders

// 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)
}
开发者ID:HackLinux,项目名称:nimbus.io,代码行数:27,代码来源:connection.go

示例4: GetCorsInfo

// 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,
	}
}
开发者ID:hobbs,项目名称:go-json-rest,代码行数:30,代码来源:request.go

示例5: buildCanonicalHeaders

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")
}
开发者ID:advincze,项目名称:wercker-ecs,代码行数:29,代码来源:v4.go

示例6: TestDoPollForAsynchronous_ReturnsErrorForLastErrorResponse

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())
}
开发者ID:Azure,项目名称:go-autorest,代码行数:26,代码来源:async_test.go

示例7: TestDoPollForAsynchronous_ReturnsAnUnknownErrorForFailedOperations

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())
}
开发者ID:Azure,项目名称:go-autorest,代码行数:26,代码来源:async_test.go

示例8: initiateBlobUpload

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
}
开发者ID:CodingDance,项目名称:harbor,代码行数:35,代码来源:repository.go

示例9: extractMetadataFromHeader

// 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
}
开发者ID:balamurugana,项目名称:minio,代码行数:26,代码来源:handler-utils.go

示例10: AddResponseDiffToRW

// 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
}
开发者ID:Comcast,项目名称:golang-money,代码行数:31,代码来源:httpConn.go

示例11: PushManifest

// 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 = &registry_error.Error{
		StatusCode: resp.StatusCode,
		Detail:     string(b),
	}

	return
}
开发者ID:vmware,项目名称:harbor,代码行数:34,代码来源:repository.go

示例12: initiateBlobUpload

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 = &registry_error.Error{
		StatusCode: resp.StatusCode,
		Detail:     string(b),
	}

	return
}
开发者ID:vmware,项目名称:harbor,代码行数:30,代码来源:repository.go

示例13: All

// 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
	}
}
开发者ID:brunoqc,项目名称:martian,代码行数:27,代码来源:header.go

示例14: GetLog

// 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))
}
开发者ID:yaolingling,项目名称:harbor,代码行数:32,代码来源:replication_job.go

示例15: TestHttpClientSend

// 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)
}
开发者ID:jiho2468,项目名称:go-gcm,代码行数:32,代码来源:gcm_test.go


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