本文整理汇总了Golang中net/http.Header.Get方法的典型用法代码示例。如果您正苦于以下问题:Golang Header.Get方法的具体用法?Golang Header.Get怎么用?Golang Header.Get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Header
的用法示例。
在下文中一共展示了Header.Get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ValidateSignature
func (rs *RouteServiceConfig) ValidateSignature(headers *http.Header, requestUrl string) error {
metadataHeader := headers.Get(RouteServiceMetadata)
signatureHeader := headers.Get(RouteServiceSignature)
signature, err := SignatureFromHeaders(signatureHeader, metadataHeader, rs.crypto)
if err != nil {
rs.logger.Info("proxy.route-service.current_key", lager.Data{"error": err.Error()})
// Decrypt the head again trying to use the old key.
if rs.cryptoPrev != nil {
rs.logger.Info("proxy.route-service.current_key", lager.Data{"error": err.Error()})
signature, err = SignatureFromHeaders(signatureHeader, metadataHeader, rs.cryptoPrev)
if err != nil {
rs.logger.Info("proxy.route-service.previous_key", lager.Data{"error": err.Error()})
}
}
return err
}
err = rs.validateSignatureTimeout(signature)
if err != nil {
return err
}
return rs.validateForwardedUrl(signature, requestUrl)
}
示例2: 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
}
示例3: 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
}
示例4: isVerifiedRequest
func isVerifiedRequest(header http.Header, body []byte) bool {
serverSignature := os.Getenv("SECRET")
requestSignature := header.Get("X-Hub-Signature")
// when not set up with a secret
if len(serverSignature) < 1 {
log.Println("http.request.signature.verification.skipped")
return true
}
log.Println("http.request.signature.verification.started")
if len(requestSignature) < 1 {
log.Println("http.request.signature.verification.failed", "missing X-Hub-Signature header")
return false
}
mac := hmac.New(sha1.New, []byte(serverSignature))
mac.Write(body)
expectedMAC := mac.Sum(nil)
expectedSignature := "sha1=" + hex.EncodeToString(expectedMAC)
signatureMatched := hmac.Equal([]byte(expectedSignature), []byte(requestSignature))
if signatureMatched {
log.Println("http.request.signature.verification.passed")
} else {
log.Println("http.request.signature.verification.failed")
}
return signatureMatched
}
示例5: checkHeaderValue
func checkHeaderValue(h http.Header, key, expected string) error {
actual := h.Get(key)
if actual != expected {
return fmt.Errorf("Unexpected header value for %q: %q, expected %q", key, actual, expected)
}
return nil
}
示例6: 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
}
示例7: intHeader
func intHeader(key string, h http.Header) (int, error) {
if header := h.Get(key); header != "" {
return strconv.Atoi(header)
} else {
return 0, errNoHeader
}
}
示例8: TestCustomRewriter
func (s *FwdSuite) TestCustomRewriter(c *C) {
var outHeaders http.Header
srv := testutils.NewHandler(func(w http.ResponseWriter, req *http.Request) {
outHeaders = req.Header
w.Write([]byte("hello"))
})
defer srv.Close()
f, err := New(Rewriter(&HeaderRewriter{TrustForwardHeader: false, Hostname: "hello"}))
c.Assert(err, IsNil)
proxy := testutils.NewHandler(func(w http.ResponseWriter, req *http.Request) {
req.URL = testutils.ParseURI(srv.URL)
f.ServeHTTP(w, req)
})
defer proxy.Close()
headers := http.Header{
XForwardedProto: []string{"httpx"},
XForwardedFor: []string{"192.168.1.1"},
}
re, _, err := testutils.Get(proxy.URL, testutils.Headers(headers))
c.Assert(err, IsNil)
c.Assert(re.StatusCode, Equals, http.StatusOK)
c.Assert(outHeaders.Get(XForwardedProto), Equals, "http")
c.Assert(strings.Contains(outHeaders.Get(XForwardedFor), "192.168.1.1"), Equals, false)
}
示例9: uploadFileReadParam
func uploadFileReadParam(header *http.Header) (*meta.MetaInfo, string, error) {
path := header.Get(headerPath)
fragmentIndex := header.Get(headerIndex)
bytesRange := header.Get(headerRange)
isLast := header.Get(headerIsLast)
version := header.Get(headerVersion)
start, end, err := splitRange(bytesRange)
if err != nil {
fmt.Errorf("[OSS]splitRange error: %s \n", err)
return nil, version, err
}
last := false
if isLast == "true" || isLast == "TRUE" {
last = true
}
index, err := strconv.ParseUint(fragmentIndex, 10, 64)
if err != nil {
fmt.Errorf("[OSS]parse fragmentIndex error: %s \n", err)
return nil, version, err
}
fmt.Printf("[OSS][uploadFileReadParam] path: %s, fragmentIndex: %d, bytesRange: %d-%d, isLast: %v \n", path, index, start, end, last)
metaInfoValue := &meta.MetaInfoValue{
Index: index,
Start: start,
End: end,
IsLast: last,
}
metaInfo := &meta.MetaInfo{Path: path, Value: metaInfoValue}
return metaInfo, version, nil
}
示例10: NewDecoder
// NewDecor returns a new decoder based on the HTTP header.
func NewDecoder(r io.Reader, h http.Header) (Decoder, error) {
ct := h.Get(hdrContentType)
mediatype, params, err := mime.ParseMediaType(ct)
if err != nil {
return nil, fmt.Errorf("invalid Content-Type header %q: %s", ct, err)
}
const (
protoType = ProtoType + "/" + ProtoSubType
textType = "text/plain"
)
switch mediatype {
case protoType:
if p := params["proto"]; p != ProtoProtocol {
return nil, fmt.Errorf("unrecognized protocol message %s", p)
}
if e := params["encoding"]; e != "delimited" {
return nil, fmt.Errorf("unsupported encoding %s", e)
}
return &protoDecoder{r: r}, nil
case textType:
if v, ok := params["version"]; ok && v != "0.0.4" {
return nil, fmt.Errorf("unrecognized protocol version %s", v)
}
return &textDecoder{r: r}, nil
default:
return nil, fmt.Errorf("unsupported media type %q, expected %q or %q", mediatype, protoType, textType)
}
}
示例11: certExpirationTime
// certExpirationTime computes a cert freshness based on Cache-Control
// and Age headers of h.
//
// Returns 0 if one of the required headers is not present or cert lifetime
// is expired.
func certExpirationTime(h http.Header) time.Duration {
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 indicates only
// a comma-separated header is valid, so it should be fine to split this on
// commas.
var max int
for _, entry := range strings.Split(h.Get("Cache-Control"), ",") {
max = maxAge(entry)
if max > 0 {
break
}
}
if max <= 0 {
return 0
}
age, err := strconv.Atoi(h.Get("Age"))
if err != nil {
return 0
}
remainingTime := max - age
if remainingTime <= 0 {
return 0
}
return time.Duration(remainingTime) * time.Second
}
示例12: ValidateSignature
func (rs *RouteServiceConfig) ValidateSignature(headers *http.Header) error {
metadataHeader := headers.Get(RouteServiceMetadata)
signatureHeader := headers.Get(RouteServiceSignature)
signature, err := SignatureFromHeaders(signatureHeader, metadataHeader, rs.crypto)
if err != nil {
rs.logger.Warnd(map[string]interface{}{"error": err.Error()}, "proxy.route-service.current_key")
// Decrypt the head again trying to use the old key.
if rs.cryptoPrev != nil {
rs.logger.Warnd(map[string]interface{}{"error": err.Error()}, "proxy.route-service.current_key")
signature, err = SignatureFromHeaders(signatureHeader, metadataHeader, rs.cryptoPrev)
if err != nil {
rs.logger.Warnd(map[string]interface{}{"error": err.Error()}, "proxy.route-service.previous_key")
}
}
return err
}
err = rs.validateSignatureTimeout(signature)
if err != nil {
return err
}
return rs.validateForwardedUrl(signature, headers)
}
示例13: baseURI
func baseURI(h *http.Header) string {
baseURI := h.Get("X-Requested-Uri")
if strings.HasSuffix(baseURI, "/") {
baseURI = baseURI[:len(baseURI)-1]
}
return baseURI
}
示例14: readHeaderFileInfo
func (b *B2) readHeaderFileInfo(header http.Header) (*FileInfo, error) {
var err error
info := &FileInfo{conn: b}
info.AccountID = b.AccountID
info.Type = header.Get("Content-Type")
info.ID = header.Get("X-Bz-File-Id")
info.Length, err = strconv.ParseInt(header.Get("Content-Length"), 10, 64)
if err != nil {
return nil, err
}
info.Name, err = url.QueryUnescape(header.Get("X-Bz-File-Name"))
if err != nil {
return nil, err
}
info.Sha1 = header.Get("X-Bz-Content-Sha1")
for headerName, val := range header {
if !strings.HasPrefix(headerName, HeaderInfoPrefix) {
continue
}
// B2 does not support multiple values per header
info.Info[headerName[len(HeaderInfoPrefix):]] = val[0]
}
return info, nil
}
示例15: 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
}