copy.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package httpheaders
  2. import "net/http"
  3. // Copy copies specified headers from one header to another.
  4. func Copy(from, to http.Header, only []string) {
  5. for _, key := range only {
  6. key = http.CanonicalHeaderKey(key)
  7. if values := from[key]; len(values) > 0 {
  8. to[key] = append([]string(nil), values...)
  9. }
  10. }
  11. }
  12. // CopyAll copies all headers from one header to another.
  13. func CopyAll(from, to http.Header, overwrite bool) {
  14. for key, values := range from {
  15. // Keys in http.Header are already canonicalized, so no need for http.CanonicalHeaderKey here
  16. if !overwrite && len(to.Values(key)) > 0 {
  17. continue
  18. }
  19. if len(values) > 0 {
  20. to[key] = append([]string(nil), values...)
  21. }
  22. }
  23. }
  24. // CopyFromRequest copies specified headers from the http.Request to the provided header.
  25. func CopyFromRequest(req *http.Request, header http.Header, only []string) {
  26. for _, key := range only {
  27. key = http.CanonicalHeaderKey(key)
  28. if key == Host {
  29. header.Set(key, req.Host)
  30. continue
  31. }
  32. if values := req.Header[key]; len(values) > 0 {
  33. header[key] = append([]string(nil), values...)
  34. }
  35. }
  36. }
  37. // CopyToRequest copies headers from the provided header to the http.Request.
  38. func CopyToRequest(header http.Header, req *http.Request) {
  39. for key, values := range header {
  40. if len(values) == 0 {
  41. continue
  42. }
  43. // Keys in http.Header are already canonicalized, so no need for http.CanonicalHeaderKey here
  44. if key == Host {
  45. req.Host = values[0]
  46. } else {
  47. req.Header[key] = append([]string(nil), values...)
  48. }
  49. }
  50. }