adaptor.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. // Package fasthttpadaptor provides helper functions for converting net/http
  2. // request handlers to fasthttp request handlers.
  3. package fasthttpadaptor
  4. import (
  5. "bufio"
  6. "io"
  7. "net"
  8. "net/http"
  9. "sync"
  10. "github.com/valyala/fasthttp"
  11. )
  12. // NewFastHTTPHandlerFunc wraps net/http handler func to fasthttp
  13. // request handler, so it can be passed to fasthttp server.
  14. //
  15. // While this function may be used for easy switching from net/http to fasthttp,
  16. // it has the following drawbacks comparing to using manually written fasthttp
  17. // request handler:
  18. //
  19. // - A lot of useful functionality provided by fasthttp is missing
  20. // from net/http handler.
  21. // - net/http -> fasthttp handler conversion has some overhead,
  22. // so the returned handler will be always slower than manually written
  23. // fasthttp handler.
  24. //
  25. // So it is advisable using this function only for quick net/http -> fasthttp
  26. // switching. Then manually convert net/http handlers to fasthttp handlers
  27. // according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .
  28. func NewFastHTTPHandlerFunc(h http.HandlerFunc) fasthttp.RequestHandler {
  29. return NewFastHTTPHandler(h)
  30. }
  31. // NewFastHTTPHandler wraps net/http handler to fasthttp request handler,
  32. // so it can be passed to fasthttp server.
  33. //
  34. // While this function may be used for easy switching from net/http to fasthttp,
  35. // it has the following drawbacks comparing to using manually written fasthttp
  36. // request handler:
  37. //
  38. // - A lot of useful functionality provided by fasthttp is missing
  39. // from net/http handler.
  40. // - net/http -> fasthttp handler conversion has some overhead,
  41. // so the returned handler will be always slower than manually written
  42. // fasthttp handler.
  43. //
  44. // So it is advisable using this function only for quick net/http -> fasthttp
  45. // switching. Then manually convert net/http handlers to fasthttp handlers
  46. // according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .
  47. func NewFastHTTPHandler(h http.Handler) fasthttp.RequestHandler {
  48. return func(ctx *fasthttp.RequestCtx) {
  49. var r http.Request
  50. if err := ConvertRequest(ctx, &r, true); err != nil {
  51. ctx.Logger().Printf("cannot parse requestURI %q: %v", r.RequestURI, err)
  52. ctx.Error("Internal Server Error", fasthttp.StatusInternalServerError)
  53. return
  54. }
  55. w := netHTTPResponseWriter{
  56. w: ctx.Response.BodyWriter(),
  57. ctx: ctx,
  58. }
  59. h.ServeHTTP(&w, r.WithContext(ctx))
  60. ctx.SetStatusCode(w.StatusCode())
  61. haveContentType := false
  62. for k, vv := range w.Header() {
  63. if k == fasthttp.HeaderContentType {
  64. haveContentType = true
  65. }
  66. for _, v := range vv {
  67. ctx.Response.Header.Add(k, v)
  68. }
  69. }
  70. if !haveContentType {
  71. // From net/http.ResponseWriter.Write:
  72. // If the Header does not contain a Content-Type line, Write adds a Content-Type set
  73. // to the result of passing the initial 512 bytes of written data to DetectContentType.
  74. l := 512
  75. b := ctx.Response.Body()
  76. if len(b) < 512 {
  77. l = len(b)
  78. }
  79. ctx.Response.Header.Set(fasthttp.HeaderContentType, http.DetectContentType(b[:l]))
  80. }
  81. }
  82. }
  83. type netHTTPResponseWriter struct {
  84. w io.Writer
  85. h http.Header
  86. ctx *fasthttp.RequestCtx
  87. statusCode int
  88. }
  89. func (w *netHTTPResponseWriter) StatusCode() int {
  90. if w.statusCode == 0 {
  91. return http.StatusOK
  92. }
  93. return w.statusCode
  94. }
  95. func (w *netHTTPResponseWriter) Header() http.Header {
  96. if w.h == nil {
  97. w.h = make(http.Header)
  98. }
  99. return w.h
  100. }
  101. func (w *netHTTPResponseWriter) WriteHeader(statusCode int) {
  102. w.statusCode = statusCode
  103. }
  104. func (w *netHTTPResponseWriter) Write(p []byte) (int, error) {
  105. return w.w.Write(p)
  106. }
  107. func (w *netHTTPResponseWriter) Flush() {}
  108. type wrappedConn struct {
  109. net.Conn
  110. wg sync.WaitGroup
  111. once sync.Once
  112. }
  113. func (c *wrappedConn) Close() (err error) {
  114. c.once.Do(func() {
  115. err = c.Conn.Close()
  116. c.wg.Done()
  117. })
  118. return
  119. }
  120. func (w *netHTTPResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  121. // Hijack assumes control of the connection, so we need to prevent fasthttp from closing it or
  122. // doing anything else with it.
  123. w.ctx.HijackSetNoResponse(true)
  124. conn := &wrappedConn{Conn: w.ctx.Conn()}
  125. conn.wg.Add(1)
  126. w.ctx.Hijack(func(net.Conn) {
  127. conn.wg.Wait()
  128. })
  129. bufW := bufio.NewWriter(conn)
  130. // Write any unflushed body to the hijacked connection buffer.
  131. unflushedBody := w.ctx.Response.Body()
  132. if len(unflushedBody) > 0 {
  133. if _, err := bufW.Write(unflushedBody); err != nil {
  134. conn.Close()
  135. return nil, nil, err
  136. }
  137. }
  138. return conn, &bufio.ReadWriter{Reader: bufio.NewReader(conn), Writer: bufW}, nil
  139. }