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


Golang Header.Set方法代码示例

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


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

示例1: quakeTechnicalProto

// fetches SC3ML and turns it into a protobuf.
func quakeTechnicalProto(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result {
	if res := weft.CheckQuery(r, []string{}, []string{}); !res.Ok {
		return res
	}

	by, res := getBytes(s3+strings.TrimPrefix(r.URL.Path, "/quake/technical/")+".xml", "")
	if !res.Ok {
		return res
	}

	q, err := sc3ml.QuakeTechnical(by)
	if err != nil {
		return weft.ServiceUnavailableError(err)
	}

	m, err := proto.Marshal(&q)
	if err != nil {
		return weft.ServiceUnavailableError(err)
	}

	b.Write(m)

	h.Set("Content-Type", protobuf)
	return &weft.StatusOK
}
开发者ID:gclitheroe,项目名称:haz,代码行数:26,代码来源:quakeProto.go

示例2: TestWarning

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

示例3: createSubStream

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

}
开发者ID:zhaohaidao,项目名称:libchan,代码行数:28,代码来源:session.go

示例4: TestRespMustRevalidate

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)
}
开发者ID:kr,项目名称:httpcache,代码行数:7,代码来源:httpcache_test.go

示例5: GetUploadBytesSize

// 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
}
开发者ID:aerofs,项目名称:aerofs-sdk-golang,代码行数:26,代码来源:file.go

示例6: populateViaHeader

func populateViaHeader(header http.Header, httpVersion string) {
	via := httpVersion + " router"
	if prior, ok := header["Via"]; ok {
		via = strings.Join(prior, ", ") + ", " + via
	}
	header.Set("Via", via)
}
开发者ID:lukaszraczylo,项目名称:router,代码行数:7,代码来源:backend_handler.go

示例7: fakeClientWith

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
	})
}
开发者ID:FlyWings,项目名称:kubernetes,代码行数:25,代码来源:builder_test.go

示例8: TestJWTAuthenticationWrongToken

func TestJWTAuthenticationWrongToken(t *testing.T) {
	m := minion.Classic(minion.Options{JWTToken: "123"})

	usersHandler := func(ctx *minion.Context) {
		j := struct {
			Message string `json:"message"`
		}{
			"ok",
		}
		ctx.JSON(200, j)
	}

	m.Get("/users", usersHandler)

	ts := httptest.NewServer(m)
	defer ts.Close()

	var j, body string
	var status int

	tokenAuth := jwtauth.New("HS256", []byte("wrong"), nil)
	_, tokenString, _ := tokenAuth.Encode(nil)

	h := http.Header{}
	h.Set("Authorization", "BEARER "+tokenString)

	status, body = tst.Request(t, ts, "GET", "/users", h, nil)
	tst.AssertEqual(t, 401, status)

	j = `{"status":401,"message":"Unauthorized"}`
	tst.AssertEqual(t, j, body)
}
开发者ID:ustrajunior,项目名称:minion,代码行数:32,代码来源:router_test.go

示例9: createFakeInfo

func createFakeInfo(name string, labels map[string]string) *resource.Info {
	pod := createFakePod(name, labels)
	marshaledObj, _ := json.Marshal(pod)

	mapping := &meta.RESTMapping{
		Resource: name,
		Scope:    meta.RESTScopeNamespace,
		GroupVersionKind: unversioned.GroupVersionKind{
			Kind:    "Pod",
			Version: "v1",
		}}

	client := &fake.RESTClient{
		Codec: testapi.Default.Codec(),
		Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
			header := http.Header{}
			header.Set("Content-Type", runtime.ContentTypeJSON)
			return &http.Response{
				StatusCode: 200,
				Header:     header,
				Body:       ioutil.NopCloser(bytes.NewReader(marshaledObj)),
			}, nil
		})}
	info := resource.NewInfo(client, mapping, "default", "nginx", false)

	info.Object = pod

	return info
}
开发者ID:runseb,项目名称:helm,代码行数:29,代码来源:client_test.go

示例10: setAllowHeader

// setAllowHeader builds a Allow header based on the resource configuration.
func setAllowHeader(headers http.Header, isItem bool, conf resource.Conf) {
	methods := []string{}
	if isItem {
		// Methods are sorted
		if conf.IsModeAllowed(resource.Update) {
			methods = append(methods, "DELETE")
		}
		if conf.IsModeAllowed(resource.Read) {
			methods = append(methods, "GET, HEAD")
		}
		if conf.IsModeAllowed(resource.Update) {
			methods = append(methods, "PATCH")
			// See http://tools.ietf.org/html/rfc5789#section-3
			headers.Set("Allow-Patch", "application/json")
		}
		if conf.IsModeAllowed(resource.Create) || conf.IsModeAllowed(resource.Replace) {
			methods = append(methods, "PUT")
		}
	} else {
		// Methods are sorted
		if conf.IsModeAllowed(resource.Clear) {
			methods = append(methods, "DELETE")
		}
		if conf.IsModeAllowed(resource.List) {
			methods = append(methods, "GET, HEAD")
		}
		if conf.IsModeAllowed(resource.Create) {
			methods = append(methods, "POST")
		}
	}
	if len(methods) > 0 {
		headers.Set("Allow", strings.Join(methods, ", "))
	}
}
开发者ID:rs,项目名称:rest-layer,代码行数:35,代码来源:util.go

示例11: TestJWTAuthentication

func TestJWTAuthentication(t *testing.T) {
	m := minion.Classic(minion.Options{JWTToken: "123"})

	usersHandler := func(ctx *minion.Context) {
		j := struct {
			Message string `json:"message"`
		}{
			"ok",
		}
		ctx.JSON(200, j)
	}

	m.Get("/users", usersHandler)

	ts := httptest.NewServer(m)
	defer ts.Close()

	var j, body string
	var status int

	tokenString, _ := minion.CreateJWTToken(nil)

	h := http.Header{}
	h.Set("Authorization", "BEARER "+tokenString)

	status, body = tst.Request(t, ts, "GET", "/users", h, nil)
	tst.AssertEqual(t, 200, status)

	j = `{"message":"ok"}`
	tst.AssertEqual(t, j, body)
}
开发者ID:ustrajunior,项目名称:minion,代码行数:31,代码来源:router_test.go

示例12: TestEnv

func TestEnv(t *testing.T) {
	for k, c := range []struct {
		expectedIP    string
		expectedOwner string
		expectedUA    string
		request       *http.Request
		owner         string
		headers       map[string]string
	}{
		{"1234", "peter", "firefox", &http.Request{RemoteAddr: "1234"}, "peter", map[string]string{"user-Agent": "firefox"}},
		{"1234", "peter", "", &http.Request{RemoteAddr: "4321"}, "peter", map[string]string{"x-FoRwarded-FoR": "1234"}},
		{"1234", "peter", "firefox", &http.Request{RemoteAddr: "4321"}, "peter", map[string]string{"x-FoRwarded-FoR": "1234", "user-Agent": "firefox"}},
	} {
		h := http.Header{}
		for y, x := range c.headers {
			h.Set(y, x)
		}
		r := c.request
		r.Header = h
		t.Logf("%v", r)
		e := NewEnv(r)
		e.Owner(c.owner)
		assert.Equal(t, c.expectedIP, e.Ctx().ClientIP, "Case %d", k)
		assert.Equal(t, c.expectedOwner, e.Ctx().Owner, "Case %d", k)
		assert.Equal(t, c.expectedUA, e.Ctx().UserAgent, "Case %d", k)
	}
}
开发者ID:lmineiro,项目名称:hydra,代码行数:27,代码来源:env_test.go

示例13: worker

// Here's the worker, of which we'll run several concurrent instances. Each
// worker will periodically make requests to the site to simulate users
// playing with it
func worker(done chan<- bool) {
	// First connect to the WebSocket server
	dialer := websocket.DefaultDialer
	header := http.Header{}
	header.Set("Origin", "http://bsprague.com")
	conn, _, err := dialer.Dial("ws://192.168.2.1:8080/ws", header)
	if err != nil {
		fmt.Println("Error connecting to server", err)
		done <- true
		return
	}

	defer conn.Close()
	go readLoop(conn)

	// Tick regularly somewhere between every 25 and 75 ms
	ticker := time.NewTicker(time.Millisecond * time.Duration(rand.Int63n(500)+250))

	for _ = range ticker.C {
		if err := conn.WriteJSON(randomBlock()); err != nil {
			fmt.Println("Error sending block", err)
			done <- true
			return
		}
	}

	done <- true
}
开发者ID:bcspragu,项目名称:SDPServe,代码行数:31,代码来源:main.go

示例14: SetViaHeader

// SetViaHeader sets the Via header.
//
// If Via is already present, via is appended to
// the existing value.
//
// http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-14#section-9.9
func SetViaHeader(header http.Header, via string) {
	if v := header.Get("Via"); v != "" {
		via = v + ", " + via
	}

	header.Set("Via", via)
}
开发者ID:eolexe,项目名称:martian,代码行数:13,代码来源:proxyutil.go

示例15: queryImages

func (imageService Service) queryImages(includeDetails bool, imagesResponseContainer interface{}, queryParameters *QueryParameters) error {
	urlPostFix := "/images"
	if includeDetails {
		urlPostFix = urlPostFix + "/detail"
	}

	reqURL, err := buildQueryURL(imageService, queryParameters, urlPostFix)
	if err != nil {
		return err
	}

	var headers http.Header = http.Header{}
	headers.Set("Accept", "application/json")
	resp, err := imageService.Session.Get(reqURL.String(), nil, &headers)
	if err != nil {
		return err
	}

	err = util.CheckHTTPResponseStatusCode(resp)
	if err != nil {
		return err
	}

	rbody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return errors.New("aaa")
	}
	if err = json.Unmarshal(rbody, &imagesResponseContainer); err != nil {
		return err
	}
	return nil
}
开发者ID:christoffetzer,项目名称:golang-client,代码行数:32,代码来源:image.go


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