github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/transports/fast/adaptor.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 */ 17 18 package fast 19 20 import ( 21 "github.com/aacfactory/fns/context" 22 "github.com/aacfactory/fns/transports" 23 "github.com/valyala/fasthttp" 24 "sync" 25 "time" 26 ) 27 28 var ( 29 ctxPool = sync.Pool{} 30 ) 31 32 func handlerAdaptor(h transports.Handler, writeTimeout time.Duration) fasthttp.RequestHandler { 33 return func(ctx *fasthttp.RequestCtx) { 34 var c *Context 35 cc := ctxPool.Get() 36 if cc == nil { 37 cc = &Context{ 38 locals: make(context.Entries, 0, 1), 39 } 40 } 41 c = cc.(*Context) 42 c.RequestCtx = ctx 43 r := Request{ 44 Context: c, 45 } 46 result := transports.AcquireResultResponseWriter(writeTimeout, r.Header().Get(transports.ContentTypeHeaderName)) 47 w := ResponseWriter{ 48 Context: c, 49 result: result, 50 } 51 52 h.Handle(&w, &r) 53 ctx.SetStatusCode(w.Status()) 54 w.result.Header().Foreach(func(key []byte, values [][]byte) { 55 for _, value := range values { 56 ctx.Response.Header.AddBytesKV(key, value) 57 } 58 }) 59 if bodyLen := w.BodyLen(); bodyLen > 0 { 60 body := w.Body() 61 n := 0 62 for n < bodyLen { 63 nn, writeErr := ctx.Write(body[n:]) 64 if writeErr != nil { 65 break 66 } 67 n += nn 68 } 69 } 70 if !w.Hijacked() { 71 // release result 72 transports.ReleaseResultResponseWriter(result) 73 // release ctx 74 c.RequestCtx = nil 75 c.locals.Reset() 76 ctxPool.Put(c) 77 } 78 } 79 }