adaptor.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. "fmt"
  7. "io"
  8. "net"
  9. "net/http"
  10. "sync"
  11. "sync/atomic"
  12. "github.com/valyala/fasthttp"
  13. )
  14. // NewFastHTTPHandlerFunc wraps net/http handler func to fasthttp
  15. // request handler, so it can be passed to fasthttp server.
  16. //
  17. // While this function may be used for easy switching from net/http to fasthttp,
  18. // it has the following drawbacks comparing to using manually written fasthttp
  19. // request handler:
  20. //
  21. // - A lot of useful functionality provided by fasthttp is missing
  22. // from net/http handler.
  23. // - net/http -> fasthttp handler conversion has some overhead,
  24. // so the returned handler will be always slower than manually written
  25. // fasthttp handler.
  26. //
  27. // So it is advisable using this function only for quick net/http -> fasthttp
  28. // switching. Then manually convert net/http handlers to fasthttp handlers
  29. // according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .
  30. func NewFastHTTPHandlerFunc(h http.HandlerFunc) fasthttp.RequestHandler {
  31. return NewFastHTTPHandler(h)
  32. }
  33. // NewFastHTTPHandler wraps net/http handler to fasthttp request handler,
  34. // so it can be passed to fasthttp server.
  35. //
  36. // While this function may be used for easy switching from net/http to fasthttp,
  37. // it has the following drawbacks comparing to using manually written fasthttp
  38. // request handler:
  39. //
  40. // - A lot of useful functionality provided by fasthttp is missing
  41. // from net/http handler.
  42. // - net/http -> fasthttp handler conversion has some overhead,
  43. // so the returned handler will be always slower than manually written
  44. // fasthttp handler.
  45. //
  46. // So it is advisable using this function only for quick net/http -> fasthttp
  47. // switching. Then manually convert net/http handlers to fasthttp handlers
  48. // according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .
  49. func NewFastHTTPHandler(h http.Handler) fasthttp.RequestHandler {
  50. return func(ctx *fasthttp.RequestCtx) {
  51. var r http.Request
  52. if err := ConvertRequest(ctx, &r, true); err != nil {
  53. ctx.Logger().Printf("cannot parse requestURI %q: %v", r.RequestURI, err)
  54. ctx.Error("Internal Server Error", fasthttp.StatusInternalServerError)
  55. return
  56. }
  57. w := acquireWriter(ctx)
  58. // Serve the net/http handler concurrently so we can react to Flush/Hijack.
  59. go func() {
  60. defer func() {
  61. if rec := recover(); rec != nil {
  62. ctx.Logger().Printf("panic in net/http handler: %v", rec)
  63. select {
  64. case w.modeCh <- modePanicked:
  65. default:
  66. }
  67. } else {
  68. // Signal completion if no other mode was selected yet.
  69. select {
  70. case w.modeCh <- modeDone:
  71. default:
  72. }
  73. }
  74. _ = w.Close()
  75. }()
  76. h.ServeHTTP(w, r.WithContext(ctx))
  77. }()
  78. // Decide mode by first event.
  79. switch <-w.modeCh {
  80. case modeDone:
  81. // Buffered, no Flush() nor Hijack().
  82. ctx.SetStatusCode(w.status())
  83. haveContentType := false
  84. for k, vv := range w.Header() {
  85. if k == fasthttp.HeaderContentType {
  86. haveContentType = true
  87. }
  88. for _, v := range vv {
  89. ctx.Response.Header.Add(k, v)
  90. }
  91. }
  92. if !haveContentType {
  93. // From net/http.ResponseWriter.Write:
  94. // If the Header does not contain a Content-Type line, Write adds a Content-Type set
  95. // to the result of passing the initial 512 bytes of written data to DetectContentType.
  96. l := min(len(w.responseBody), 512)
  97. if l > 0 {
  98. ctx.Response.Header.Set(fasthttp.HeaderContentType, http.DetectContentType(w.responseBody[:l]))
  99. }
  100. }
  101. if len(w.responseBody) > 0 {
  102. ctx.Response.SetBody(w.responseBody)
  103. }
  104. releaseWriter(w)
  105. case modeFlushed:
  106. // Streaming: send headers and start SetBodyStreamWriter.
  107. ctx.SetStatusCode(w.status())
  108. haveContentType := false
  109. for k, vv := range w.Header() {
  110. // No Content-Length when streaming.
  111. if k == fasthttp.HeaderContentLength {
  112. continue
  113. }
  114. if k == fasthttp.HeaderContentType {
  115. haveContentType = true
  116. }
  117. for _, v := range vv {
  118. ctx.Response.Header.Add(k, v)
  119. }
  120. }
  121. if !haveContentType {
  122. w.mu.Lock()
  123. if len(w.responseBody) > 0 {
  124. l := min(len(w.responseBody), 512)
  125. ctx.Response.Header.Set(fasthttp.HeaderContentType, http.DetectContentType(w.responseBody[:l]))
  126. }
  127. w.mu.Unlock()
  128. }
  129. ctx.SetBodyStreamWriter(func(bw *bufio.Writer) {
  130. // Ensure cleanup only after the stream completes.
  131. defer releaseWriter(w)
  132. // Send pre-flush bytes.
  133. if b := w.consumePreflush(); len(b) > 0 {
  134. _, _ = bw.Write(b)
  135. _ = bw.Flush()
  136. }
  137. // Stream subsequent writes from the pipe until EOF.
  138. buf := bufferPool.Get().(*[]byte)
  139. defer bufferPool.Put(buf)
  140. for {
  141. n, err := w.pr.Read(*buf)
  142. if n > 0 {
  143. if _, e := bw.Write((*buf)[:n]); e != nil {
  144. return
  145. }
  146. if e := bw.Flush(); e != nil {
  147. return
  148. }
  149. }
  150. if err != nil {
  151. return
  152. }
  153. }
  154. })
  155. // Signal the writer that streaming is ready so Flush() can return.
  156. close(w.streamReady)
  157. case modeHijacked:
  158. return
  159. case modePanicked:
  160. panic("net/http handler panicked")
  161. }
  162. }
  163. }
  164. var bufferPool = sync.Pool{
  165. New: func() any {
  166. b := make([]byte, 32*1024)
  167. return &b
  168. },
  169. }
  170. const (
  171. modeDone = iota + 1
  172. modeFlushed
  173. modeHijacked
  174. modePanicked
  175. )
  176. // Writer implements http.ResponseWriter + http.Flusher + http.Hijacker for the adaptor.
  177. type writer struct {
  178. ctx *fasthttp.RequestCtx
  179. h http.Header
  180. statusCode atomic.Int64
  181. mu sync.Mutex
  182. responseBody []byte
  183. bufPool *[]byte
  184. pr *io.PipeReader
  185. pw *io.PipeWriter
  186. hijacked atomic.Bool
  187. modeCh chan int
  188. streamReady chan struct{}
  189. flushOnce sync.Once
  190. closeOnce sync.Once
  191. }
  192. func acquireWriter(ctx *fasthttp.RequestCtx) *writer {
  193. pr, pw := io.Pipe()
  194. return &writer{
  195. ctx: ctx,
  196. h: make(http.Header),
  197. responseBody: nil,
  198. pr: pr,
  199. pw: pw,
  200. modeCh: make(chan int, 1),
  201. streamReady: make(chan struct{}),
  202. }
  203. }
  204. func releaseWriter(w *writer) {
  205. _ = w.Close()
  206. if w.bufPool != nil {
  207. bufferPool.Put(w.bufPool)
  208. w.bufPool = nil
  209. }
  210. }
  211. func (w *writer) Header() http.Header {
  212. return w.h
  213. }
  214. func (w *writer) WriteHeader(code int) {
  215. // Allow the same codes as net/http.
  216. if code < 100 || code > 999 {
  217. panic(fmt.Sprintf("invalid WriteHeader code %v", code))
  218. }
  219. w.statusCode.CompareAndSwap(0, int64(code))
  220. }
  221. func (w *writer) Write(p []byte) (int, error) {
  222. select {
  223. case <-w.streamReady:
  224. return w.pw.Write(p)
  225. default:
  226. }
  227. w.mu.Lock()
  228. defer w.mu.Unlock()
  229. if w.responseBody == nil {
  230. w.bufPool = bufferPool.Get().(*[]byte)
  231. w.responseBody = (*w.bufPool)[:0]
  232. }
  233. w.responseBody = append(w.responseBody, p...)
  234. return len(p), nil
  235. }
  236. func (w *writer) Flush() {
  237. w.flushOnce.Do(func() {
  238. select {
  239. case w.modeCh <- modeFlushed:
  240. default:
  241. }
  242. })
  243. <-w.streamReady
  244. }
  245. type wrappedConn struct {
  246. net.Conn
  247. wg sync.WaitGroup
  248. once sync.Once
  249. }
  250. func (c *wrappedConn) Close() (err error) {
  251. c.once.Do(func() {
  252. err = c.Conn.Close()
  253. c.wg.Done()
  254. })
  255. return err
  256. }
  257. func (w *writer) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  258. if !w.hijacked.CompareAndSwap(false, true) {
  259. return nil, nil, http.ErrHijacked
  260. }
  261. // Tell fasthttp not to send any HTTP response before hijacking.
  262. w.ctx.HijackSetNoResponse(true)
  263. conn := &wrappedConn{Conn: w.ctx.Conn()}
  264. conn.wg.Add(1)
  265. w.ctx.Hijack(func(net.Conn) {
  266. conn.wg.Wait()
  267. })
  268. bufW := bufio.NewWriter(conn)
  269. // Write any unflushed body to the hijacked connection buffer.
  270. unflushedBody := w.consumePreflush()
  271. if len(unflushedBody) > 0 {
  272. if _, err := bufW.Write(unflushedBody); err != nil {
  273. _ = conn.Close()
  274. return nil, nil, err
  275. }
  276. }
  277. select {
  278. case w.modeCh <- modeHijacked:
  279. default:
  280. }
  281. return conn, &bufio.ReadWriter{Reader: bufio.NewReader(conn), Writer: bufW}, nil
  282. }
  283. func (w *writer) Close() error {
  284. w.closeOnce.Do(func() {
  285. _ = w.pw.Close()
  286. _ = w.pr.Close()
  287. })
  288. return nil
  289. }
  290. // status returns the effective status code (defaults to 200).
  291. func (w *writer) status() int {
  292. code := int(w.statusCode.Load())
  293. if code == 0 {
  294. return http.StatusOK
  295. }
  296. return code
  297. }
  298. // consumePreflush returns pre-flush bytes and clears the buffer.
  299. func (w *writer) consumePreflush() []byte {
  300. w.mu.Lock()
  301. defer w.mu.Unlock()
  302. if len(w.responseBody) == 0 {
  303. return nil
  304. }
  305. out := w.responseBody
  306. w.responseBody = nil
  307. return out
  308. }