本文整理汇总了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
}
示例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)
}
}
示例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
}
示例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)
}
示例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
}
示例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)
}
示例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
})
}
示例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)
}
示例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
}
示例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, ", "))
}
}
示例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)
}
示例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)
}
}
示例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
}
示例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)
}
示例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
}