response.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package h2quic
  2. import (
  3. "bytes"
  4. "errors"
  5. "io/ioutil"
  6. "net/http"
  7. "net/textproto"
  8. "strconv"
  9. "strings"
  10. "golang.org/x/net/http2"
  11. )
  12. // copied from net/http2/transport.go
  13. var errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
  14. var noBody = ioutil.NopCloser(bytes.NewReader(nil))
  15. // from the handleResponse function
  16. func responseFromHeaders(f *http2.MetaHeadersFrame) (*http.Response, error) {
  17. if f.Truncated {
  18. return nil, errResponseHeaderListSize
  19. }
  20. status := f.PseudoValue("status")
  21. if status == "" {
  22. return nil, errors.New("missing status pseudo header")
  23. }
  24. statusCode, err := strconv.Atoi(status)
  25. if err != nil {
  26. return nil, errors.New("malformed non-numeric status pseudo header")
  27. }
  28. // TODO: handle statusCode == 100
  29. header := make(http.Header)
  30. res := &http.Response{
  31. Proto: "HTTP/2.0",
  32. ProtoMajor: 2,
  33. Header: header,
  34. StatusCode: statusCode,
  35. Status: status + " " + http.StatusText(statusCode),
  36. }
  37. for _, hf := range f.RegularFields() {
  38. key := http.CanonicalHeaderKey(hf.Name)
  39. if key == "Trailer" {
  40. t := res.Trailer
  41. if t == nil {
  42. t = make(http.Header)
  43. res.Trailer = t
  44. }
  45. foreachHeaderElement(hf.Value, func(v string) {
  46. t[http.CanonicalHeaderKey(v)] = nil
  47. })
  48. } else {
  49. header[key] = append(header[key], hf.Value)
  50. }
  51. }
  52. return res, nil
  53. }
  54. // continuation of the handleResponse function
  55. func setLength(res *http.Response, isHead, streamEnded bool) *http.Response {
  56. if !streamEnded || isHead {
  57. res.ContentLength = -1
  58. if clens := res.Header["Content-Length"]; len(clens) == 1 {
  59. if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
  60. res.ContentLength = clen64
  61. }
  62. }
  63. }
  64. return res
  65. }
  66. // copied from net/http/server.go
  67. // foreachHeaderElement splits v according to the "#rule" construction
  68. // in RFC 2616 section 2.1 and calls fn for each non-empty element.
  69. func foreachHeaderElement(v string, fn func(string)) {
  70. v = textproto.TrimString(v)
  71. if v == "" {
  72. return
  73. }
  74. if !strings.Contains(v, ",") {
  75. fn(v)
  76. return
  77. }
  78. for _, f := range strings.Split(v, ",") {
  79. if f = textproto.TrimString(f); f != "" {
  80. fn(f)
  81. }
  82. }
  83. }