github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/metadata/http.go (about) 1 package metadata 2 3 import ( 4 "net/http" 5 "strings" 6 ) 7 8 var xPrefixKey = "x-md-" 9 10 // SetHTTPPrefixKey update http header prefix with `key`, default is 'x-md-' 11 // 12 // 设置http header中metadata的前缀,默认是'x-md-' 13 func SetHTTPPrefixKey(key string) { 14 xPrefixKey = key 15 } 16 17 func (md Metadata) HTTPHeader() http.Header { 18 h := http.Header{} 19 for k, v := range md { 20 h.Add("x-md-"+k, v) 21 } 22 return h 23 } 24 25 // IncomingHTTPHeader retrieve Metadata from an HTTPHeader header 26 // 27 // 从HTTP头中取出Metadata 28 func IncomingHTTPHeader(h http.Header) Metadata { 29 md := Metadata{} 30 for k, vs := range h { 31 if strings.HasPrefix(k, xPrefixKey) { 32 md[k] = strings.Join(vs, ",") 33 } 34 } 35 return md 36 } 37 38 // OutgoingHTTPHeader append Metadata to an HTTPHeader header 39 // 40 // 向HTTP头中加入Metadata 41 func OutgoingHTTPHeader(md Metadata, h http.Header) http.Header { 42 for k, v := range md { 43 h.Add(xPrefixKey+k, v) 44 } 45 return h 46 } 47 48 // IncomingHTTPRequest retrieve Metadata from an HTTPHeader request 49 // 50 // 从HTTP请求中取出Metadata 51 func IncomingHTTPRequest(r *http.Request) Metadata { 52 md := Metadata{} 53 for k, vs := range r.Header { 54 if strings.HasPrefix(k, xPrefixKey) { 55 md[k] = strings.Join(vs, ",") 56 } 57 } 58 return md 59 } 60 61 // OutgoingHTTPRequest append Metadata to an HTTPHeader request 62 // 63 // 向HTTP请求中加入Metadata 64 func OutgoingHTTPRequest(md Metadata, r *http.Request) *http.Request { 65 for k, v := range md { 66 r.Header.Add(xPrefixKey+k, v) 67 } 68 return r 69 } 70 71 // IncomingHTTPResponse retrieve Metadata from an HTTPHeader response 72 // 73 // 从HTTP响应中取出Metadata 74 func IncomingHTTPResponse(r *http.Response) Metadata { 75 md := Metadata{} 76 for k, vs := range r.Header { 77 if strings.HasPrefix(k, xPrefixKey) { 78 md[k] = strings.Join(vs, ",") 79 } 80 } 81 return md 82 } 83 84 // OutgoingHTTPResponse append Metadata to an HTTPHeader response 85 // 86 // 向HTTP响应中加入Metadata 87 func OutgoingHTTPResponse(md Metadata, r *http.Response) *http.Response { 88 for k, v := range md { 89 r.Header.Add(xPrefixKey+k, v) 90 } 91 return r 92 }