copy.go 1.5 KB

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