本文整理汇总了Golang中net/http.Header类的典型用法代码示例。如果您正苦于以下问题:Golang Header类的具体用法?Golang Header怎么用?Golang Header使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Header类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestSampleWithRequestHeaders
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)
}
}
示例2: prepareReq
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
}
示例3: isContentType
// 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
}
示例4: GetResponse
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
}
示例5: 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
}
示例6: 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)
}
}
示例7: createHeaders
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
}
示例8: intHeader
func intHeader(key string, h http.Header) (int, error) {
if header := h.Get(key); header != "" {
return strconv.Atoi(header)
} else {
return 0, errNoHeader
}
}
示例9: copyHeader
func copyHeader(source http.Header, dest *http.Header) {
for n, v := range source {
for _, vv := range v {
dest.Add(n, vv)
}
}
}
示例10: cacheAge
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
}
示例11: timeHeader
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
}
}
示例12: ParseLXDFileHeaders
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_
}
示例13: CopyHeaders
// 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)
}
}
}
示例14: SignedInId
// 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
}
示例15: assertHeaders
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))
}
}
}