ctx.go 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991
  1. // ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
  2. // 🤖 Github Repository: https://github.com/gofiber/fiber
  3. // 📌 API Documentation: https://docs.gofiber.io
  4. package fiber
  5. import (
  6. "bytes"
  7. "context"
  8. "crypto/tls"
  9. "encoding/xml"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "mime/multipart"
  14. "net"
  15. "net/http"
  16. "path/filepath"
  17. "reflect"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "text/template"
  22. "time"
  23. "github.com/gofiber/fiber/v2/internal/schema"
  24. "github.com/gofiber/fiber/v2/utils"
  25. "github.com/valyala/bytebufferpool"
  26. "github.com/valyala/fasthttp"
  27. )
  28. const (
  29. schemeHTTP = "http"
  30. schemeHTTPS = "https"
  31. )
  32. // maxParams defines the maximum number of parameters per route.
  33. const maxParams = 30
  34. // Some constants for BodyParser, QueryParser, CookieParser and ReqHeaderParser.
  35. const (
  36. queryTag = "query"
  37. reqHeaderTag = "reqHeader"
  38. bodyTag = "form"
  39. paramsTag = "params"
  40. cookieTag = "cookie"
  41. )
  42. // userContextKey define the key name for storing context.Context in *fasthttp.RequestCtx
  43. const userContextKey = "__local_user_context__"
  44. var (
  45. // decoderPoolMap helps to improve BodyParser's, QueryParser's, CookieParser's and ReqHeaderParser's performance
  46. decoderPoolMap = map[string]*sync.Pool{}
  47. // tags is used to classify parser's pool
  48. tags = []string{queryTag, bodyTag, reqHeaderTag, paramsTag, cookieTag}
  49. )
  50. func init() {
  51. for _, tag := range tags {
  52. decoderPoolMap[tag] = &sync.Pool{New: func() interface{} {
  53. return decoderBuilder(ParserConfig{
  54. IgnoreUnknownKeys: true,
  55. ZeroEmpty: true,
  56. })
  57. }}
  58. }
  59. }
  60. // SetParserDecoder allow globally change the option of form decoder, update decoderPool
  61. func SetParserDecoder(parserConfig ParserConfig) {
  62. for _, tag := range tags {
  63. decoderPoolMap[tag] = &sync.Pool{New: func() interface{} {
  64. return decoderBuilder(parserConfig)
  65. }}
  66. }
  67. }
  68. // Ctx represents the Context which hold the HTTP request and response.
  69. // It has methods for the request query string, parameters, body, HTTP headers and so on.
  70. type Ctx struct {
  71. app *App // Reference to *App
  72. route *Route // Reference to *Route
  73. indexRoute int // Index of the current route
  74. indexHandler int // Index of the current handler
  75. method string // HTTP method
  76. methodINT int // HTTP method INT equivalent
  77. baseURI string // HTTP base uri
  78. path string // HTTP path with the modifications by the configuration -> string copy from pathBuffer
  79. pathBuffer []byte // HTTP path buffer
  80. detectionPath string // Route detection path -> string copy from detectionPathBuffer
  81. detectionPathBuffer []byte // HTTP detectionPath buffer
  82. treePath string // Path for the search in the tree
  83. pathOriginal string // Original HTTP path
  84. values [maxParams]string // Route parameter values
  85. fasthttp *fasthttp.RequestCtx // Reference to *fasthttp.RequestCtx
  86. matched bool // Non use route matched
  87. viewBindMap sync.Map // Default view map to bind template engine
  88. }
  89. // TLSHandler object
  90. type TLSHandler struct {
  91. clientHelloInfo *tls.ClientHelloInfo
  92. }
  93. // GetClientInfo Callback function to set ClientHelloInfo
  94. // Must comply with the method structure of https://cs.opensource.google/go/go/+/refs/tags/go1.20:src/crypto/tls/common.go;l=554-563
  95. // Since we overlay the method of the tls config in the listener method
  96. func (t *TLSHandler) GetClientInfo(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
  97. t.clientHelloInfo = info
  98. return nil, nil //nolint:nilnil // Not returning anything useful here is probably fine
  99. }
  100. // Range data for c.Range
  101. type Range struct {
  102. Type string
  103. Ranges []RangeSet
  104. }
  105. // RangeSet represents a single content range from a request.
  106. type RangeSet struct {
  107. Start int
  108. End int
  109. }
  110. // Cookie data for c.Cookie
  111. type Cookie struct {
  112. Name string `json:"name"`
  113. Value string `json:"value"`
  114. Path string `json:"path"`
  115. Domain string `json:"domain"`
  116. MaxAge int `json:"max_age"`
  117. Expires time.Time `json:"expires"`
  118. Secure bool `json:"secure"`
  119. HTTPOnly bool `json:"http_only"`
  120. SameSite string `json:"same_site"`
  121. SessionOnly bool `json:"session_only"`
  122. }
  123. // Views is the interface that wraps the Render function.
  124. type Views interface {
  125. Load() error
  126. Render(io.Writer, string, interface{}, ...string) error
  127. }
  128. // ParserType require two element, type and converter for register.
  129. // Use ParserType with BodyParser for parsing custom type in form data.
  130. type ParserType struct {
  131. Customtype interface{}
  132. Converter func(string) reflect.Value
  133. }
  134. // ParserConfig form decoder config for SetParserDecoder
  135. type ParserConfig struct {
  136. IgnoreUnknownKeys bool
  137. SetAliasTag string
  138. ParserType []ParserType
  139. ZeroEmpty bool
  140. }
  141. // AcquireCtx retrieves a new Ctx from the pool.
  142. func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) *Ctx {
  143. c, ok := app.pool.Get().(*Ctx)
  144. if !ok {
  145. panic(fmt.Errorf("failed to type-assert to *Ctx"))
  146. }
  147. // Set app reference
  148. c.app = app
  149. // Reset route and handler index
  150. c.indexRoute = -1
  151. c.indexHandler = 0
  152. // Reset matched flag
  153. c.matched = false
  154. // Set paths
  155. c.pathOriginal = app.getString(fctx.URI().PathOriginal())
  156. // Set method
  157. c.method = app.getString(fctx.Request.Header.Method())
  158. c.methodINT = app.methodInt(c.method)
  159. // Attach *fasthttp.RequestCtx to ctx
  160. c.fasthttp = fctx
  161. // reset base uri
  162. c.baseURI = ""
  163. // Prettify path
  164. c.configDependentPaths()
  165. return c
  166. }
  167. // ReleaseCtx releases the ctx back into the pool.
  168. func (app *App) ReleaseCtx(c *Ctx) {
  169. // Reset values
  170. c.route = nil
  171. c.fasthttp = nil
  172. c.viewBindMap = sync.Map{}
  173. app.pool.Put(c)
  174. }
  175. // Accepts checks if the specified extensions or content types are acceptable.
  176. func (c *Ctx) Accepts(offers ...string) string {
  177. return getOffer(c.Get(HeaderAccept), acceptsOfferType, offers...)
  178. }
  179. // AcceptsCharsets checks if the specified charset is acceptable.
  180. func (c *Ctx) AcceptsCharsets(offers ...string) string {
  181. return getOffer(c.Get(HeaderAcceptCharset), acceptsOffer, offers...)
  182. }
  183. // AcceptsEncodings checks if the specified encoding is acceptable.
  184. func (c *Ctx) AcceptsEncodings(offers ...string) string {
  185. return getOffer(c.Get(HeaderAcceptEncoding), acceptsOffer, offers...)
  186. }
  187. // AcceptsLanguages checks if the specified language is acceptable.
  188. func (c *Ctx) AcceptsLanguages(offers ...string) string {
  189. return getOffer(c.Get(HeaderAcceptLanguage), acceptsOffer, offers...)
  190. }
  191. // App returns the *App reference to the instance of the Fiber application
  192. func (c *Ctx) App() *App {
  193. return c.app
  194. }
  195. // Append the specified value to the HTTP response header field.
  196. // If the header is not already set, it creates the header with the specified value.
  197. func (c *Ctx) Append(field string, values ...string) {
  198. if len(values) == 0 {
  199. return
  200. }
  201. h := c.app.getString(c.fasthttp.Response.Header.Peek(field))
  202. originalH := h
  203. for _, value := range values {
  204. if len(h) == 0 {
  205. h = value
  206. } else if h != value && !strings.HasPrefix(h, value+",") && !strings.HasSuffix(h, " "+value) &&
  207. !strings.Contains(h, " "+value+",") {
  208. h += ", " + value
  209. }
  210. }
  211. if originalH != h {
  212. c.Set(field, h)
  213. }
  214. }
  215. // Attachment sets the HTTP response Content-Disposition header field to attachment.
  216. func (c *Ctx) Attachment(filename ...string) {
  217. if len(filename) > 0 {
  218. fname := filepath.Base(filename[0])
  219. c.Type(filepath.Ext(fname))
  220. c.setCanonical(HeaderContentDisposition, `attachment; filename="`+c.app.quoteString(fname)+`"`)
  221. return
  222. }
  223. c.setCanonical(HeaderContentDisposition, "attachment")
  224. }
  225. // BaseURL returns (protocol + host + base path).
  226. func (c *Ctx) BaseURL() string {
  227. // TODO: Could be improved: 53.8 ns/op 32 B/op 1 allocs/op
  228. // Should work like https://codeigniter.com/user_guide/helpers/url_helper.html
  229. if c.baseURI != "" {
  230. return c.baseURI
  231. }
  232. c.baseURI = c.Protocol() + "://" + c.Hostname()
  233. return c.baseURI
  234. }
  235. // BodyRaw contains the raw body submitted in a POST request.
  236. // Returned value is only valid within the handler. Do not store any references.
  237. // Make copies or use the Immutable setting instead.
  238. func (c *Ctx) BodyRaw() []byte {
  239. return c.getBody()
  240. }
  241. func (c *Ctx) tryDecodeBodyInOrder(
  242. originalBody *[]byte,
  243. encodings []string,
  244. ) ([]byte, uint8, error) {
  245. var (
  246. err error
  247. body []byte
  248. decodesRealized uint8
  249. )
  250. for index, encoding := range encodings {
  251. decodesRealized++
  252. switch encoding {
  253. case StrGzip:
  254. body, err = c.fasthttp.Request.BodyGunzip()
  255. case StrBr, StrBrotli:
  256. body, err = c.fasthttp.Request.BodyUnbrotli()
  257. case StrDeflate:
  258. body, err = c.fasthttp.Request.BodyInflate()
  259. default:
  260. decodesRealized--
  261. if len(encodings) == 1 {
  262. body = c.fasthttp.Request.Body()
  263. }
  264. return body, decodesRealized, nil
  265. }
  266. if err != nil {
  267. return nil, decodesRealized, err
  268. }
  269. // Only execute body raw update if it has a next iteration to try to decode
  270. if index < len(encodings)-1 && decodesRealized > 0 {
  271. if index == 0 {
  272. tempBody := c.fasthttp.Request.Body()
  273. *originalBody = make([]byte, len(tempBody))
  274. copy(*originalBody, tempBody)
  275. }
  276. c.fasthttp.Request.SetBodyRaw(body)
  277. }
  278. }
  279. return body, decodesRealized, nil
  280. }
  281. // Body contains the raw body submitted in a POST request.
  282. // This method will decompress the body if the 'Content-Encoding' header is provided.
  283. // It returns the original (or decompressed) body data which is valid only within the handler.
  284. // Don't store direct references to the returned data.
  285. // If you need to keep the body's data later, make a copy or use the Immutable option.
  286. func (c *Ctx) Body() []byte {
  287. var (
  288. err error
  289. body, originalBody []byte
  290. headerEncoding string
  291. encodingOrder = []string{"", "", ""}
  292. )
  293. // faster than peek
  294. c.Request().Header.VisitAll(func(key, value []byte) {
  295. if c.app.getString(key) == HeaderContentEncoding {
  296. headerEncoding = c.app.getString(value)
  297. }
  298. })
  299. // Split and get the encodings list, in order to attend the
  300. // rule defined at: https://www.rfc-editor.org/rfc/rfc9110#section-8.4-5
  301. encodingOrder = getSplicedStrList(headerEncoding, encodingOrder)
  302. if len(encodingOrder) == 0 {
  303. return c.getBody()
  304. }
  305. var decodesRealized uint8
  306. body, decodesRealized, err = c.tryDecodeBodyInOrder(&originalBody, encodingOrder)
  307. // Ensure that the body will be the original
  308. if originalBody != nil && decodesRealized > 0 {
  309. c.fasthttp.Request.SetBodyRaw(originalBody)
  310. }
  311. if err != nil {
  312. return []byte(err.Error())
  313. }
  314. if c.app.config.Immutable {
  315. return utils.CopyBytes(body)
  316. }
  317. return body
  318. }
  319. func decoderBuilder(parserConfig ParserConfig) interface{} {
  320. decoder := schema.NewDecoder()
  321. decoder.IgnoreUnknownKeys(parserConfig.IgnoreUnknownKeys)
  322. if parserConfig.SetAliasTag != "" {
  323. decoder.SetAliasTag(parserConfig.SetAliasTag)
  324. }
  325. for _, v := range parserConfig.ParserType {
  326. decoder.RegisterConverter(reflect.ValueOf(v.Customtype).Interface(), v.Converter)
  327. }
  328. decoder.ZeroEmpty(parserConfig.ZeroEmpty)
  329. return decoder
  330. }
  331. // BodyParser binds the request body to a struct.
  332. // It supports decoding the following content types based on the Content-Type header:
  333. // application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data
  334. // All JSON extenstion mime types are supported (eg. application/problem+json)
  335. // If none of the content types above are matched, it will return a ErrUnprocessableEntity error
  336. func (c *Ctx) BodyParser(out interface{}) error {
  337. // Get content-type
  338. ctype := utils.ToLower(c.app.getString(c.fasthttp.Request.Header.ContentType()))
  339. ctype = utils.ParseVendorSpecificContentType(ctype)
  340. // Only use ctype string up to and excluding byte ';'
  341. ctypeEnd := strings.IndexByte(ctype, ';')
  342. if ctypeEnd != -1 {
  343. ctype = ctype[:ctypeEnd]
  344. }
  345. // Parse body accordingly
  346. if strings.HasSuffix(ctype, "json") {
  347. return c.app.config.JSONDecoder(c.Body(), out)
  348. }
  349. if ctype == MIMEApplicationForm {
  350. data := make(map[string][]string)
  351. var err error
  352. c.fasthttp.PostArgs().VisitAll(func(key, val []byte) {
  353. if err != nil {
  354. return
  355. }
  356. k := c.app.getString(key)
  357. v := c.app.getString(val)
  358. err = formatParserData(out, data, bodyTag, k, v, c.app.config.EnableSplittingOnParsers, true)
  359. })
  360. if err != nil {
  361. return err
  362. }
  363. return c.parseToStruct(bodyTag, out, data)
  364. }
  365. if ctype == MIMEMultipartForm {
  366. multipartForm, err := c.fasthttp.MultipartForm()
  367. if err != nil {
  368. return err
  369. }
  370. data := make(map[string][]string)
  371. for key, values := range multipartForm.Value {
  372. err = formatParserData(out, data, bodyTag, key, values, c.app.config.EnableSplittingOnParsers, true)
  373. if err != nil {
  374. return err
  375. }
  376. }
  377. return c.parseToStruct(bodyTag, out, data)
  378. }
  379. if ctype == MIMETextXML || ctype == MIMEApplicationXML {
  380. if err := xml.Unmarshal(c.Body(), out); err != nil {
  381. return fmt.Errorf("failed to unmarshal: %w", err)
  382. }
  383. return nil
  384. }
  385. // No suitable content type found
  386. return ErrUnprocessableEntity
  387. }
  388. // ClearCookie expires a specific cookie by key on the client side.
  389. // If no key is provided it expires all cookies that came with the request.
  390. func (c *Ctx) ClearCookie(key ...string) {
  391. if len(key) > 0 {
  392. for i := range key {
  393. c.fasthttp.Response.Header.DelClientCookie(key[i])
  394. }
  395. return
  396. }
  397. c.fasthttp.Request.Header.VisitAllCookie(func(k, v []byte) {
  398. c.fasthttp.Response.Header.DelClientCookieBytes(k)
  399. })
  400. }
  401. // Context returns *fasthttp.RequestCtx that carries a deadline
  402. // a cancellation signal, and other values across API boundaries.
  403. func (c *Ctx) Context() *fasthttp.RequestCtx {
  404. return c.fasthttp
  405. }
  406. // UserContext returns a context implementation that was set by
  407. // user earlier or returns a non-nil, empty context,if it was not set earlier.
  408. func (c *Ctx) UserContext() context.Context {
  409. ctx, ok := c.fasthttp.UserValue(userContextKey).(context.Context)
  410. if !ok {
  411. ctx = context.Background()
  412. c.SetUserContext(ctx)
  413. }
  414. return ctx
  415. }
  416. // SetUserContext sets a context implementation by user.
  417. func (c *Ctx) SetUserContext(ctx context.Context) {
  418. c.fasthttp.SetUserValue(userContextKey, ctx)
  419. }
  420. // Cookie sets a cookie by passing a cookie struct.
  421. func (c *Ctx) Cookie(cookie *Cookie) {
  422. fcookie := fasthttp.AcquireCookie()
  423. fcookie.SetKey(cookie.Name)
  424. fcookie.SetValue(cookie.Value)
  425. fcookie.SetPath(cookie.Path)
  426. fcookie.SetDomain(cookie.Domain)
  427. // only set max age and expiry when SessionOnly is false
  428. // i.e. cookie supposed to last beyond browser session
  429. // refer: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_the_lifetime_of_a_cookie
  430. if !cookie.SessionOnly {
  431. fcookie.SetMaxAge(cookie.MaxAge)
  432. fcookie.SetExpire(cookie.Expires)
  433. }
  434. fcookie.SetSecure(cookie.Secure)
  435. fcookie.SetHTTPOnly(cookie.HTTPOnly)
  436. switch utils.ToLower(cookie.SameSite) {
  437. case CookieSameSiteStrictMode:
  438. fcookie.SetSameSite(fasthttp.CookieSameSiteStrictMode)
  439. case CookieSameSiteNoneMode:
  440. fcookie.SetSameSite(fasthttp.CookieSameSiteNoneMode)
  441. case CookieSameSiteDisabled:
  442. fcookie.SetSameSite(fasthttp.CookieSameSiteDisabled)
  443. default:
  444. fcookie.SetSameSite(fasthttp.CookieSameSiteLaxMode)
  445. }
  446. c.fasthttp.Response.Header.SetCookie(fcookie)
  447. fasthttp.ReleaseCookie(fcookie)
  448. }
  449. // Cookies are used for getting a cookie value by key.
  450. // Defaults to the empty string "" if the cookie doesn't exist.
  451. // If a default value is given, it will return that value if the cookie doesn't exist.
  452. // The returned value is only valid within the handler. Do not store any references.
  453. // Make copies or use the Immutable setting to use the value outside the Handler.
  454. func (c *Ctx) Cookies(key string, defaultValue ...string) string {
  455. return defaultString(c.app.getString(c.fasthttp.Request.Header.Cookie(key)), defaultValue)
  456. }
  457. // CookieParser is used to bind cookies to a struct
  458. func (c *Ctx) CookieParser(out interface{}) error {
  459. data := make(map[string][]string)
  460. var err error
  461. // loop through all cookies
  462. c.fasthttp.Request.Header.VisitAllCookie(func(key, val []byte) {
  463. if err != nil {
  464. return
  465. }
  466. k := c.app.getString(key)
  467. v := c.app.getString(val)
  468. err = formatParserData(out, data, cookieTag, k, v, c.app.config.EnableSplittingOnParsers, true)
  469. })
  470. if err != nil {
  471. return err
  472. }
  473. return c.parseToStruct(cookieTag, out, data)
  474. }
  475. // Download transfers the file from path as an attachment.
  476. // Typically, browsers will prompt the user for download.
  477. // By default, the Content-Disposition header filename= parameter is the filepath (this typically appears in the browser dialog).
  478. // Override this default with the filename parameter.
  479. func (c *Ctx) Download(file string, filename ...string) error {
  480. var fname string
  481. if len(filename) > 0 {
  482. fname = filename[0]
  483. } else {
  484. fname = filepath.Base(file)
  485. }
  486. c.setCanonical(HeaderContentDisposition, `attachment; filename="`+c.app.quoteString(fname)+`"`)
  487. return c.SendFile(file)
  488. }
  489. // Request return the *fasthttp.Request object
  490. // This allows you to use all fasthttp request methods
  491. // https://godoc.org/github.com/valyala/fasthttp#Request
  492. func (c *Ctx) Request() *fasthttp.Request {
  493. return &c.fasthttp.Request
  494. }
  495. // Response return the *fasthttp.Response object
  496. // This allows you to use all fasthttp response methods
  497. // https://godoc.org/github.com/valyala/fasthttp#Response
  498. func (c *Ctx) Response() *fasthttp.Response {
  499. return &c.fasthttp.Response
  500. }
  501. // Format performs content-negotiation on the Accept HTTP header.
  502. // It uses Accepts to select a proper format.
  503. // If the header is not specified or there is no proper format, text/plain is used.
  504. func (c *Ctx) Format(body interface{}) error {
  505. // Get accepted content type
  506. accept := c.Accepts("html", "json", "txt", "xml")
  507. // Set accepted content type
  508. c.Type(accept)
  509. // Type convert provided body
  510. var b string
  511. switch val := body.(type) {
  512. case string:
  513. b = val
  514. case []byte:
  515. b = c.app.getString(val)
  516. default:
  517. b = fmt.Sprintf("%v", val)
  518. }
  519. // Format based on the accept content type
  520. switch accept {
  521. case "html":
  522. return c.SendString("<p>" + b + "</p>")
  523. case "json":
  524. return c.JSON(body)
  525. case "txt":
  526. return c.SendString(b)
  527. case "xml":
  528. return c.XML(body)
  529. }
  530. return c.SendString(b)
  531. }
  532. // FormFile returns the first file by key from a MultipartForm.
  533. func (c *Ctx) FormFile(key string) (*multipart.FileHeader, error) {
  534. return c.fasthttp.FormFile(key)
  535. }
  536. // FormValue returns the first value by key from a MultipartForm.
  537. // Search is performed in QueryArgs, PostArgs, MultipartForm and FormFile in this particular order.
  538. // Defaults to the empty string "" if the form value doesn't exist.
  539. // If a default value is given, it will return that value if the form value does not exist.
  540. // Returned value is only valid within the handler. Do not store any references.
  541. // Make copies or use the Immutable setting instead.
  542. func (c *Ctx) FormValue(key string, defaultValue ...string) string {
  543. return defaultString(c.app.getString(c.fasthttp.FormValue(key)), defaultValue)
  544. }
  545. // Fresh returns true when the response is still “fresh” in the client's cache,
  546. // otherwise false is returned to indicate that the client cache is now stale
  547. // and the full response should be sent.
  548. // When a client sends the Cache-Control: no-cache request header to indicate an end-to-end
  549. // reload request, this module will return false to make handling these requests transparent.
  550. // https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33
  551. func (c *Ctx) Fresh() bool {
  552. // fields
  553. modifiedSince := c.Get(HeaderIfModifiedSince)
  554. noneMatch := c.Get(HeaderIfNoneMatch)
  555. // unconditional request
  556. if modifiedSince == "" && noneMatch == "" {
  557. return false
  558. }
  559. // Always return stale when Cache-Control: no-cache
  560. // to support end-to-end reload requests
  561. // https://tools.ietf.org/html/rfc2616#section-14.9.4
  562. cacheControl := c.Get(HeaderCacheControl)
  563. if cacheControl != "" && isNoCache(cacheControl) {
  564. return false
  565. }
  566. // if-none-match
  567. if noneMatch != "" && noneMatch != "*" {
  568. etag := c.app.getString(c.fasthttp.Response.Header.Peek(HeaderETag))
  569. if etag == "" {
  570. return false
  571. }
  572. if c.app.isEtagStale(etag, c.app.getBytes(noneMatch)) {
  573. return false
  574. }
  575. if modifiedSince != "" {
  576. lastModified := c.app.getString(c.fasthttp.Response.Header.Peek(HeaderLastModified))
  577. if lastModified != "" {
  578. lastModifiedTime, err := http.ParseTime(lastModified)
  579. if err != nil {
  580. return false
  581. }
  582. modifiedSinceTime, err := http.ParseTime(modifiedSince)
  583. if err != nil {
  584. return false
  585. }
  586. return lastModifiedTime.Before(modifiedSinceTime)
  587. }
  588. }
  589. }
  590. return true
  591. }
  592. // Get returns the HTTP request header specified by field.
  593. // Field names are case-insensitive
  594. // Returned value is only valid within the handler. Do not store any references.
  595. // Make copies or use the Immutable setting instead.
  596. func (c *Ctx) Get(key string, defaultValue ...string) string {
  597. return defaultString(c.app.getString(c.fasthttp.Request.Header.Peek(key)), defaultValue)
  598. }
  599. // GetRespHeader returns the HTTP response header specified by field.
  600. // Field names are case-insensitive
  601. // Returned value is only valid within the handler. Do not store any references.
  602. // Make copies or use the Immutable setting instead.
  603. func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string {
  604. return defaultString(c.app.getString(c.fasthttp.Response.Header.Peek(key)), defaultValue)
  605. }
  606. // GetReqHeaders returns the HTTP request headers.
  607. // Returned value is only valid within the handler. Do not store any references.
  608. // Make copies or use the Immutable setting instead.
  609. func (c *Ctx) GetReqHeaders() map[string][]string {
  610. headers := make(map[string][]string)
  611. c.Request().Header.VisitAll(func(k, v []byte) {
  612. key := c.app.getString(k)
  613. headers[key] = append(headers[key], c.app.getString(v))
  614. })
  615. return headers
  616. }
  617. // GetRespHeaders returns the HTTP response headers.
  618. // Returned value is only valid within the handler. Do not store any references.
  619. // Make copies or use the Immutable setting instead.
  620. func (c *Ctx) GetRespHeaders() map[string][]string {
  621. headers := make(map[string][]string)
  622. c.Response().Header.VisitAll(func(k, v []byte) {
  623. key := c.app.getString(k)
  624. headers[key] = append(headers[key], c.app.getString(v))
  625. })
  626. return headers
  627. }
  628. // Hostname contains the hostname derived from the X-Forwarded-Host or Host HTTP header.
  629. // Returned value is only valid within the handler. Do not store any references.
  630. // Make copies or use the Immutable setting instead.
  631. // Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.
  632. func (c *Ctx) Hostname() string {
  633. if c.IsProxyTrusted() {
  634. if host := c.Get(HeaderXForwardedHost); len(host) > 0 {
  635. commaPos := strings.Index(host, ",")
  636. if commaPos != -1 {
  637. return host[:commaPos]
  638. }
  639. return host
  640. }
  641. }
  642. return c.app.getString(c.fasthttp.Request.URI().Host())
  643. }
  644. // Port returns the remote port of the request.
  645. func (c *Ctx) Port() string {
  646. tcpaddr, ok := c.fasthttp.RemoteAddr().(*net.TCPAddr)
  647. if !ok {
  648. panic(fmt.Errorf("failed to type-assert to *net.TCPAddr"))
  649. }
  650. return strconv.Itoa(tcpaddr.Port)
  651. }
  652. // IP returns the remote IP address of the request.
  653. // If ProxyHeader and IP Validation is configured, it will parse that header and return the first valid IP address.
  654. // Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.
  655. func (c *Ctx) IP() string {
  656. if c.IsProxyTrusted() && len(c.app.config.ProxyHeader) > 0 {
  657. return c.extractIPFromHeader(c.app.config.ProxyHeader)
  658. }
  659. return c.fasthttp.RemoteIP().String()
  660. }
  661. // extractIPsFromHeader will return a slice of IPs it found given a header name in the order they appear.
  662. // When IP validation is enabled, any invalid IPs will be omitted.
  663. func (c *Ctx) extractIPsFromHeader(header string) []string {
  664. // TODO: Reuse the c.extractIPFromHeader func somehow in here
  665. headerValue := c.Get(header)
  666. // We can't know how many IPs we will return, but we will try to guess with this constant division.
  667. // Counting ',' makes function slower for about 50ns in general case.
  668. const maxEstimatedCount = 8
  669. estimatedCount := len(headerValue) / maxEstimatedCount
  670. if estimatedCount > maxEstimatedCount {
  671. estimatedCount = maxEstimatedCount // Avoid big allocation on big header
  672. }
  673. ipsFound := make([]string, 0, estimatedCount)
  674. i := 0
  675. j := -1
  676. iploop:
  677. for {
  678. var v4, v6 bool
  679. // Manually splitting string without allocating slice, working with parts directly
  680. i, j = j+1, j+2
  681. if j > len(headerValue) {
  682. break
  683. }
  684. for j < len(headerValue) && headerValue[j] != ',' {
  685. if headerValue[j] == ':' {
  686. v6 = true
  687. } else if headerValue[j] == '.' {
  688. v4 = true
  689. }
  690. j++
  691. }
  692. for i < j && (headerValue[i] == ' ' || headerValue[i] == ',') {
  693. i++
  694. }
  695. s := utils.TrimRight(headerValue[i:j], ' ')
  696. if c.app.config.EnableIPValidation {
  697. // Skip validation if IP is clearly not IPv4/IPv6, otherwise validate without allocations
  698. if (!v6 && !v4) || (v6 && !utils.IsIPv6(s)) || (v4 && !utils.IsIPv4(s)) {
  699. continue iploop
  700. }
  701. }
  702. ipsFound = append(ipsFound, s)
  703. }
  704. return ipsFound
  705. }
  706. // extractIPFromHeader will attempt to pull the real client IP from the given header when IP validation is enabled.
  707. // currently, it will return the first valid IP address in header.
  708. // when IP validation is disabled, it will simply return the value of the header without any inspection.
  709. // Implementation is almost the same as in extractIPsFromHeader, but without allocation of []string.
  710. func (c *Ctx) extractIPFromHeader(header string) string {
  711. if c.app.config.EnableIPValidation {
  712. headerValue := c.Get(header)
  713. i := 0
  714. j := -1
  715. iploop:
  716. for {
  717. var v4, v6 bool
  718. // Manually splitting string without allocating slice, working with parts directly
  719. i, j = j+1, j+2
  720. if j > len(headerValue) {
  721. break
  722. }
  723. for j < len(headerValue) && headerValue[j] != ',' {
  724. if headerValue[j] == ':' {
  725. v6 = true
  726. } else if headerValue[j] == '.' {
  727. v4 = true
  728. }
  729. j++
  730. }
  731. for i < j && headerValue[i] == ' ' {
  732. i++
  733. }
  734. s := utils.TrimRight(headerValue[i:j], ' ')
  735. if c.app.config.EnableIPValidation {
  736. if (!v6 && !v4) || (v6 && !utils.IsIPv6(s)) || (v4 && !utils.IsIPv4(s)) {
  737. continue iploop
  738. }
  739. }
  740. return s
  741. }
  742. return c.fasthttp.RemoteIP().String()
  743. }
  744. // default behavior if IP validation is not enabled is just to return whatever value is
  745. // in the proxy header. Even if it is empty or invalid
  746. return c.Get(c.app.config.ProxyHeader)
  747. }
  748. // IPs returns a string slice of IP addresses specified in the X-Forwarded-For request header.
  749. // When IP validation is enabled, only valid IPs are returned.
  750. func (c *Ctx) IPs() []string {
  751. return c.extractIPsFromHeader(HeaderXForwardedFor)
  752. }
  753. // Is returns the matching content type,
  754. // if the incoming request's Content-Type HTTP header field matches the MIME type specified by the type parameter
  755. func (c *Ctx) Is(extension string) bool {
  756. extensionHeader := utils.GetMIME(extension)
  757. if extensionHeader == "" {
  758. return false
  759. }
  760. ct := c.app.getString(c.fasthttp.Request.Header.ContentType())
  761. if i := strings.IndexByte(ct, ';'); i != -1 {
  762. ct = ct[:i]
  763. }
  764. ct = utils.Trim(ct, ' ')
  765. return utils.EqualFold(ct, extensionHeader)
  766. }
  767. // JSON converts any interface or string to JSON.
  768. // Array and slice values encode as JSON arrays,
  769. // except that []byte encodes as a base64-encoded string,
  770. // and a nil slice encodes as the null JSON value.
  771. // If the ctype parameter is given, this method will set the
  772. // Content-Type header equal to ctype. If ctype is not given,
  773. // The Content-Type header will be set to application/json.
  774. func (c *Ctx) JSON(data interface{}, ctype ...string) error {
  775. raw, err := c.app.config.JSONEncoder(data)
  776. if err != nil {
  777. return err
  778. }
  779. c.fasthttp.Response.SetBodyRaw(raw)
  780. if len(ctype) > 0 {
  781. c.fasthttp.Response.Header.SetContentType(ctype[0])
  782. } else {
  783. c.fasthttp.Response.Header.SetContentType(MIMEApplicationJSON)
  784. }
  785. return nil
  786. }
  787. // JSONP sends a JSON response with JSONP support.
  788. // This method is identical to JSON, except that it opts-in to JSONP callback support.
  789. // By default, the callback name is simply callback.
  790. func (c *Ctx) JSONP(data interface{}, callback ...string) error {
  791. raw, err := c.app.config.JSONEncoder(data)
  792. if err != nil {
  793. return err
  794. }
  795. var result, cb string
  796. if len(callback) > 0 {
  797. cb = callback[0]
  798. } else {
  799. cb = "callback"
  800. }
  801. result = cb + "(" + c.app.getString(raw) + ");"
  802. c.setCanonical(HeaderXContentTypeOptions, "nosniff")
  803. c.fasthttp.Response.Header.SetContentType(MIMETextJavaScriptCharsetUTF8)
  804. return c.SendString(result)
  805. }
  806. // XML converts any interface or string to XML.
  807. // This method also sets the content header to application/xml.
  808. func (c *Ctx) XML(data interface{}) error {
  809. raw, err := c.app.config.XMLEncoder(data)
  810. if err != nil {
  811. return err
  812. }
  813. c.fasthttp.Response.SetBodyRaw(raw)
  814. c.fasthttp.Response.Header.SetContentType(MIMEApplicationXML)
  815. return nil
  816. }
  817. // Links joins the links followed by the property to populate the response's Link HTTP header field.
  818. func (c *Ctx) Links(link ...string) {
  819. if len(link) == 0 {
  820. return
  821. }
  822. bb := bytebufferpool.Get()
  823. for i := range link {
  824. if i%2 == 0 {
  825. _ = bb.WriteByte('<')
  826. _, _ = bb.WriteString(link[i])
  827. _ = bb.WriteByte('>')
  828. } else {
  829. _, _ = bb.WriteString(`; rel="` + link[i] + `",`)
  830. }
  831. }
  832. c.setCanonical(HeaderLink, utils.TrimRight(c.app.getString(bb.Bytes()), ','))
  833. bytebufferpool.Put(bb)
  834. }
  835. // Locals makes it possible to pass interface{} values under keys scoped to the request
  836. // and therefore available to all following routes that match the request.
  837. //
  838. // All the values are removed from ctx after returning from the top
  839. // RequestHandler. Additionally, Close method is called on each value
  840. // implementing io.Closer before removing the value from ctx.
  841. func (c *Ctx) Locals(key interface{}, value ...interface{}) interface{} {
  842. if len(value) == 0 {
  843. return c.fasthttp.UserValue(key)
  844. }
  845. c.fasthttp.SetUserValue(key, value[0])
  846. return value[0]
  847. }
  848. // Location sets the response Location HTTP header to the specified path parameter.
  849. func (c *Ctx) Location(path string) {
  850. c.setCanonical(HeaderLocation, path)
  851. }
  852. // Method returns the HTTP request method for the context, optionally overridden by the provided argument.
  853. // If no override is given or if the provided override is not a valid HTTP method, it returns the current method from the context.
  854. // Otherwise, it updates the context's method and returns the overridden method as a string.
  855. func (c *Ctx) Method(override ...string) string {
  856. if len(override) == 0 {
  857. // Nothing to override, just return current method from context
  858. return c.method
  859. }
  860. method := utils.ToUpper(override[0])
  861. mINT := c.app.methodInt(method)
  862. if mINT == -1 {
  863. // Provided override does not valid HTTP method, no override, return current method
  864. return c.method
  865. }
  866. c.method = method
  867. c.methodINT = mINT
  868. return c.method
  869. }
  870. // MultipartForm parse form entries from binary.
  871. // This returns a map[string][]string, so given a key the value will be a string slice.
  872. func (c *Ctx) MultipartForm() (*multipart.Form, error) {
  873. return c.fasthttp.MultipartForm()
  874. }
  875. // ClientHelloInfo return CHI from context
  876. func (c *Ctx) ClientHelloInfo() *tls.ClientHelloInfo {
  877. if c.app.tlsHandler != nil {
  878. return c.app.tlsHandler.clientHelloInfo
  879. }
  880. return nil
  881. }
  882. // Next executes the next method in the stack that matches the current route.
  883. func (c *Ctx) Next() error {
  884. // Increment handler index
  885. c.indexHandler++
  886. var err error
  887. // Did we execute all route handlers?
  888. if c.indexHandler < len(c.route.Handlers) {
  889. // Continue route stack
  890. err = c.route.Handlers[c.indexHandler](c)
  891. } else {
  892. // Continue handler stack
  893. _, err = c.app.next(c)
  894. }
  895. return err
  896. }
  897. // RestartRouting instead of going to the next handler. This may be useful after
  898. // changing the request path. Note that handlers might be executed again.
  899. func (c *Ctx) RestartRouting() error {
  900. c.indexRoute = -1
  901. _, err := c.app.next(c)
  902. return err
  903. }
  904. // OriginalURL contains the original request URL.
  905. // Returned value is only valid within the handler. Do not store any references.
  906. // Make copies or use the Immutable setting to use the value outside the Handler.
  907. func (c *Ctx) OriginalURL() string {
  908. return c.app.getString(c.fasthttp.Request.Header.RequestURI())
  909. }
  910. // Params is used to get the route parameters.
  911. // Defaults to empty string "" if the param doesn't exist.
  912. // If a default value is given, it will return that value if the param doesn't exist.
  913. // Returned value is only valid within the handler. Do not store any references.
  914. // Make copies or use the Immutable setting to use the value outside the Handler.
  915. func (c *Ctx) Params(key string, defaultValue ...string) string {
  916. if key == "*" || key == "+" {
  917. key += "1"
  918. }
  919. for i := range c.route.Params {
  920. if len(key) != len(c.route.Params[i]) {
  921. continue
  922. }
  923. if c.route.Params[i] == key || (!c.app.config.CaseSensitive && utils.EqualFold(c.route.Params[i], key)) {
  924. // in case values are not here
  925. if len(c.values) <= i || len(c.values[i]) == 0 {
  926. break
  927. }
  928. return c.values[i]
  929. }
  930. }
  931. return defaultString("", defaultValue)
  932. }
  933. // AllParams Params is used to get all route parameters.
  934. // Using Params method to get params.
  935. func (c *Ctx) AllParams() map[string]string {
  936. params := make(map[string]string, len(c.route.Params))
  937. for _, param := range c.route.Params {
  938. params[param] = c.Params(param)
  939. }
  940. return params
  941. }
  942. // ParamsParser binds the param string to a struct.
  943. func (c *Ctx) ParamsParser(out interface{}) error {
  944. params := make(map[string][]string, len(c.route.Params))
  945. for _, param := range c.route.Params {
  946. params[param] = append(params[param], c.Params(param))
  947. }
  948. return c.parseToStruct(paramsTag, out, params)
  949. }
  950. // ParamsInt is used to get an integer from the route parameters
  951. // it defaults to zero if the parameter is not found or if the
  952. // parameter cannot be converted to an integer
  953. // If a default value is given, it will return that value in case the param
  954. // doesn't exist or cannot be converted to an integer
  955. func (c *Ctx) ParamsInt(key string, defaultValue ...int) (int, error) {
  956. // Use Atoi to convert the param to an int or return zero and an error
  957. value, err := strconv.Atoi(c.Params(key))
  958. if err != nil {
  959. if len(defaultValue) > 0 {
  960. return defaultValue[0], nil
  961. }
  962. return 0, fmt.Errorf("failed to convert: %w", err)
  963. }
  964. return value, nil
  965. }
  966. // Path returns the path part of the request URL.
  967. // Optionally, you could override the path.
  968. func (c *Ctx) Path(override ...string) string {
  969. if len(override) != 0 && c.path != override[0] {
  970. // Set new path to context
  971. c.pathOriginal = override[0]
  972. // Set new path to request context
  973. c.fasthttp.Request.URI().SetPath(c.pathOriginal)
  974. // Prettify path
  975. c.configDependentPaths()
  976. }
  977. return c.path
  978. }
  979. // Protocol contains the request protocol string: http or https for TLS requests.
  980. // Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.
  981. func (c *Ctx) Protocol() string {
  982. if c.fasthttp.IsTLS() {
  983. return schemeHTTPS
  984. }
  985. if !c.IsProxyTrusted() {
  986. return schemeHTTP
  987. }
  988. scheme := schemeHTTP
  989. const lenXHeaderName = 12
  990. c.fasthttp.Request.Header.VisitAll(func(key, val []byte) {
  991. if len(key) < lenXHeaderName {
  992. return // Neither "X-Forwarded-" nor "X-Url-Scheme"
  993. }
  994. switch {
  995. case bytes.HasPrefix(key, []byte("X-Forwarded-")):
  996. if bytes.Equal(key, []byte(HeaderXForwardedProto)) ||
  997. bytes.Equal(key, []byte(HeaderXForwardedProtocol)) {
  998. v := c.app.getString(val)
  999. commaPos := strings.Index(v, ",")
  1000. if commaPos != -1 {
  1001. scheme = v[:commaPos]
  1002. } else {
  1003. scheme = v
  1004. }
  1005. } else if bytes.Equal(key, []byte(HeaderXForwardedSsl)) && bytes.Equal(val, []byte("on")) {
  1006. scheme = schemeHTTPS
  1007. }
  1008. case bytes.Equal(key, []byte(HeaderXUrlScheme)):
  1009. scheme = c.app.getString(val)
  1010. }
  1011. })
  1012. return scheme
  1013. }
  1014. // Query returns the query string parameter in the url.
  1015. // Defaults to empty string "" if the query doesn't exist.
  1016. // If a default value is given, it will return that value if the query doesn't exist.
  1017. // Returned value is only valid within the handler. Do not store any references.
  1018. // Make copies or use the Immutable setting to use the value outside the Handler.
  1019. func (c *Ctx) Query(key string, defaultValue ...string) string {
  1020. return defaultString(c.app.getString(c.fasthttp.QueryArgs().Peek(key)), defaultValue)
  1021. }
  1022. // Queries returns a map of query parameters and their values.
  1023. //
  1024. // GET /?name=alex&wanna_cake=2&id=
  1025. // Queries()["name"] == "alex"
  1026. // Queries()["wanna_cake"] == "2"
  1027. // Queries()["id"] == ""
  1028. //
  1029. // GET /?field1=value1&field1=value2&field2=value3
  1030. // Queries()["field1"] == "value2"
  1031. // Queries()["field2"] == "value3"
  1032. //
  1033. // GET /?list_a=1&list_a=2&list_a=3&list_b[]=1&list_b[]=2&list_b[]=3&list_c=1,2,3
  1034. // Queries()["list_a"] == "3"
  1035. // Queries()["list_b[]"] == "3"
  1036. // Queries()["list_c"] == "1,2,3"
  1037. //
  1038. // GET /api/search?filters.author.name=John&filters.category.name=Technology&filters[customer][name]=Alice&filters[status]=pending
  1039. // Queries()["filters.author.name"] == "John"
  1040. // Queries()["filters.category.name"] == "Technology"
  1041. // Queries()["filters[customer][name]"] == "Alice"
  1042. // Queries()["filters[status]"] == "pending"
  1043. func (c *Ctx) Queries() map[string]string {
  1044. m := make(map[string]string, c.Context().QueryArgs().Len())
  1045. c.Context().QueryArgs().VisitAll(func(key, value []byte) {
  1046. m[c.app.getString(key)] = c.app.getString(value)
  1047. })
  1048. return m
  1049. }
  1050. // QueryInt returns integer value of key string parameter in the url.
  1051. // Default to empty or invalid key is 0.
  1052. //
  1053. // GET /?name=alex&wanna_cake=2&id=
  1054. // QueryInt("wanna_cake", 1) == 2
  1055. // QueryInt("name", 1) == 1
  1056. // QueryInt("id", 1) == 1
  1057. // QueryInt("id") == 0
  1058. func (c *Ctx) QueryInt(key string, defaultValue ...int) int {
  1059. // Use Atoi to convert the param to an int or return zero and an error
  1060. value, err := strconv.Atoi(c.app.getString(c.fasthttp.QueryArgs().Peek(key)))
  1061. if err != nil {
  1062. if len(defaultValue) > 0 {
  1063. return defaultValue[0]
  1064. }
  1065. return 0
  1066. }
  1067. return value
  1068. }
  1069. // QueryBool returns bool value of key string parameter in the url.
  1070. // Default to empty or invalid key is false.
  1071. //
  1072. // Get /?name=alex&want_pizza=false&id=
  1073. // QueryBool("want_pizza") == false
  1074. // QueryBool("want_pizza", true) == false
  1075. // QueryBool("name") == false
  1076. // QueryBool("name", true) == true
  1077. // QueryBool("id") == false
  1078. // QueryBool("id", true) == true
  1079. func (c *Ctx) QueryBool(key string, defaultValue ...bool) bool {
  1080. value, err := strconv.ParseBool(c.app.getString(c.fasthttp.QueryArgs().Peek(key)))
  1081. if err != nil {
  1082. if len(defaultValue) > 0 {
  1083. return defaultValue[0]
  1084. }
  1085. return false
  1086. }
  1087. return value
  1088. }
  1089. // QueryFloat returns float64 value of key string parameter in the url.
  1090. // Default to empty or invalid key is 0.
  1091. //
  1092. // GET /?name=alex&amount=32.23&id=
  1093. // QueryFloat("amount") = 32.23
  1094. // QueryFloat("amount", 3) = 32.23
  1095. // QueryFloat("name", 1) = 1
  1096. // QueryFloat("name") = 0
  1097. // QueryFloat("id", 3) = 3
  1098. func (c *Ctx) QueryFloat(key string, defaultValue ...float64) float64 {
  1099. // use strconv.ParseFloat to convert the param to a float or return zero and an error.
  1100. value, err := strconv.ParseFloat(c.app.getString(c.fasthttp.QueryArgs().Peek(key)), 64)
  1101. if err != nil {
  1102. if len(defaultValue) > 0 {
  1103. return defaultValue[0]
  1104. }
  1105. return 0
  1106. }
  1107. return value
  1108. }
  1109. // QueryParser binds the query string to a struct.
  1110. func (c *Ctx) QueryParser(out interface{}) error {
  1111. data := make(map[string][]string)
  1112. var err error
  1113. c.fasthttp.QueryArgs().VisitAll(func(key, val []byte) {
  1114. if err != nil {
  1115. return
  1116. }
  1117. k := c.app.getString(key)
  1118. v := c.app.getString(val)
  1119. err = formatParserData(out, data, queryTag, k, v, c.app.config.EnableSplittingOnParsers, true)
  1120. })
  1121. if err != nil {
  1122. return err
  1123. }
  1124. return c.parseToStruct(queryTag, out, data)
  1125. }
  1126. // ReqHeaderParser binds the request header strings to a struct.
  1127. func (c *Ctx) ReqHeaderParser(out interface{}) error {
  1128. data := make(map[string][]string)
  1129. var err error
  1130. c.fasthttp.Request.Header.VisitAll(func(key, val []byte) {
  1131. if err != nil {
  1132. return
  1133. }
  1134. k := c.app.getString(key)
  1135. v := c.app.getString(val)
  1136. err = formatParserData(out, data, reqHeaderTag, k, v, c.app.config.EnableSplittingOnParsers, false)
  1137. })
  1138. if err != nil {
  1139. return err
  1140. }
  1141. return c.parseToStruct(reqHeaderTag, out, data)
  1142. }
  1143. func (*Ctx) parseToStruct(aliasTag string, out interface{}, data map[string][]string) error {
  1144. // Get decoder from pool
  1145. schemaDecoder, ok := decoderPoolMap[aliasTag].Get().(*schema.Decoder)
  1146. if !ok {
  1147. panic(fmt.Errorf("failed to type-assert to *schema.Decoder"))
  1148. }
  1149. defer decoderPoolMap[aliasTag].Put(schemaDecoder)
  1150. // Set alias tag
  1151. schemaDecoder.SetAliasTag(aliasTag)
  1152. if err := schemaDecoder.Decode(out, data); err != nil {
  1153. return fmt.Errorf("failed to decode: %w", err)
  1154. }
  1155. return nil
  1156. }
  1157. func equalFieldType(out interface{}, kind reflect.Kind, key, tag string) bool {
  1158. outTyp := reflect.TypeOf(out).Elem()
  1159. if outTyp.Kind() != reflect.Struct {
  1160. return false
  1161. }
  1162. key = utils.ToLower(key)
  1163. return checkEqualFieldType(outTyp, kind, key, tag)
  1164. }
  1165. func checkEqualFieldType(outTyp reflect.Type, kind reflect.Kind, key, tag string) bool {
  1166. for i := 0; i < outTyp.NumField(); i++ {
  1167. typeField := outTyp.Field(i)
  1168. if typeField.Anonymous && typeField.Type.Kind() == reflect.Struct {
  1169. if checkEqualFieldType(typeField.Type, kind, key, tag) {
  1170. return true
  1171. }
  1172. }
  1173. if typeField.PkgPath != "" { // unexported field
  1174. continue
  1175. }
  1176. if typeField.Type.Kind() != kind {
  1177. continue
  1178. }
  1179. inputFieldName := typeField.Tag.Get(tag)
  1180. if inputFieldName == "" {
  1181. inputFieldName = typeField.Name
  1182. } else if idx := strings.IndexByte(inputFieldName, ','); idx > -1 {
  1183. inputFieldName = inputFieldName[:idx]
  1184. }
  1185. if utils.ToLower(inputFieldName) == key {
  1186. return true
  1187. }
  1188. }
  1189. return false
  1190. }
  1191. var (
  1192. ErrRangeMalformed = errors.New("range: malformed range header string")
  1193. ErrRangeUnsatisfiable = errors.New("range: unsatisfiable range")
  1194. )
  1195. // Range returns a struct containing the type and a slice of ranges.
  1196. func (c *Ctx) Range(size int) (Range, error) {
  1197. var (
  1198. rangeData Range
  1199. ranges string
  1200. )
  1201. rangeStr := c.Get(HeaderRange)
  1202. i := strings.IndexByte(rangeStr, '=')
  1203. if i == -1 || strings.Contains(rangeStr[i+1:], "=") {
  1204. return rangeData, ErrRangeMalformed
  1205. }
  1206. rangeData.Type = rangeStr[:i]
  1207. ranges = rangeStr[i+1:]
  1208. var (
  1209. singleRange string
  1210. moreRanges = ranges
  1211. )
  1212. for moreRanges != "" {
  1213. singleRange = moreRanges
  1214. if i := strings.IndexByte(moreRanges, ','); i >= 0 {
  1215. singleRange = moreRanges[:i]
  1216. moreRanges = moreRanges[i+1:]
  1217. } else {
  1218. moreRanges = ""
  1219. }
  1220. var (
  1221. startStr, endStr string
  1222. i int
  1223. )
  1224. if i = strings.IndexByte(singleRange, '-'); i == -1 {
  1225. return rangeData, ErrRangeMalformed
  1226. }
  1227. startStr = singleRange[:i]
  1228. endStr = singleRange[i+1:]
  1229. start, startErr := fasthttp.ParseUint(utils.UnsafeBytes(startStr))
  1230. end, endErr := fasthttp.ParseUint(utils.UnsafeBytes(endStr))
  1231. if startErr != nil { // -nnn
  1232. start = size - end
  1233. end = size - 1
  1234. } else if endErr != nil { // nnn-
  1235. end = size - 1
  1236. }
  1237. if end > size-1 { // limit last-byte-pos to current length
  1238. end = size - 1
  1239. }
  1240. if start > end || start < 0 {
  1241. continue
  1242. }
  1243. rangeData.Ranges = append(rangeData.Ranges, struct {
  1244. Start int
  1245. End int
  1246. }{
  1247. start,
  1248. end,
  1249. })
  1250. }
  1251. if len(rangeData.Ranges) < 1 {
  1252. return rangeData, ErrRangeUnsatisfiable
  1253. }
  1254. return rangeData, nil
  1255. }
  1256. // Redirect to the URL derived from the specified path, with specified status.
  1257. // If status is not specified, status defaults to 302 Found.
  1258. func (c *Ctx) Redirect(location string, status ...int) error {
  1259. c.setCanonical(HeaderLocation, location)
  1260. if len(status) > 0 {
  1261. c.Status(status[0])
  1262. } else {
  1263. c.Status(StatusFound)
  1264. }
  1265. return nil
  1266. }
  1267. // Bind Add vars to default view var map binding to template engine.
  1268. // Variables are read by the Render method and may be overwritten.
  1269. func (c *Ctx) Bind(vars Map) error {
  1270. // init viewBindMap - lazy map
  1271. for k, v := range vars {
  1272. c.viewBindMap.Store(k, v)
  1273. }
  1274. return nil
  1275. }
  1276. // getLocationFromRoute get URL location from route using parameters
  1277. func (c *Ctx) getLocationFromRoute(route Route, params Map) (string, error) {
  1278. buf := bytebufferpool.Get()
  1279. for _, segment := range route.routeParser.segs {
  1280. if !segment.IsParam {
  1281. _, err := buf.WriteString(segment.Const)
  1282. if err != nil {
  1283. return "", fmt.Errorf("failed to write string: %w", err)
  1284. }
  1285. continue
  1286. }
  1287. for key, val := range params {
  1288. isSame := key == segment.ParamName || (!c.app.config.CaseSensitive && utils.EqualFold(key, segment.ParamName))
  1289. isGreedy := segment.IsGreedy && len(key) == 1 && isInCharset(key[0], greedyParameters)
  1290. if isSame || isGreedy {
  1291. _, err := buf.WriteString(utils.ToString(val))
  1292. if err != nil {
  1293. return "", fmt.Errorf("failed to write string: %w", err)
  1294. }
  1295. }
  1296. }
  1297. }
  1298. location := buf.String()
  1299. // release buffer
  1300. bytebufferpool.Put(buf)
  1301. return location, nil
  1302. }
  1303. // GetRouteURL generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831"
  1304. func (c *Ctx) GetRouteURL(routeName string, params Map) (string, error) {
  1305. return c.getLocationFromRoute(c.App().GetRoute(routeName), params)
  1306. }
  1307. // RedirectToRoute to the Route registered in the app with appropriate parameters
  1308. // If status is not specified, status defaults to 302 Found.
  1309. // If you want to send queries to route, you must add "queries" key typed as map[string]string to params.
  1310. func (c *Ctx) RedirectToRoute(routeName string, params Map, status ...int) error {
  1311. location, err := c.getLocationFromRoute(c.App().GetRoute(routeName), params)
  1312. if err != nil {
  1313. return err
  1314. }
  1315. // Check queries
  1316. if queries, ok := params["queries"].(map[string]string); ok {
  1317. queryText := bytebufferpool.Get()
  1318. defer bytebufferpool.Put(queryText)
  1319. i := 1
  1320. for k, v := range queries {
  1321. _, _ = queryText.WriteString(k + "=" + v)
  1322. if i != len(queries) {
  1323. _, _ = queryText.WriteString("&")
  1324. }
  1325. i++
  1326. }
  1327. return c.Redirect(location+"?"+queryText.String(), status...)
  1328. }
  1329. return c.Redirect(location, status...)
  1330. }
  1331. // RedirectBack to the URL to referer
  1332. // If status is not specified, status defaults to 302 Found.
  1333. func (c *Ctx) RedirectBack(fallback string, status ...int) error {
  1334. location := c.Get(HeaderReferer)
  1335. if location == "" {
  1336. location = fallback
  1337. }
  1338. return c.Redirect(location, status...)
  1339. }
  1340. // Render a template with data and sends a text/html response.
  1341. // We support the following engines: html, amber, handlebars, mustache, pug
  1342. func (c *Ctx) Render(name string, bind interface{}, layouts ...string) error {
  1343. // Get new buffer from pool
  1344. buf := bytebufferpool.Get()
  1345. defer bytebufferpool.Put(buf)
  1346. // Initialize empty bind map if bind is nil
  1347. if bind == nil {
  1348. bind = make(Map)
  1349. }
  1350. // Pass-locals-to-views, bind, appListKeys
  1351. c.renderExtensions(bind)
  1352. var rendered bool
  1353. for i := len(c.app.mountFields.appListKeys) - 1; i >= 0; i-- {
  1354. prefix := c.app.mountFields.appListKeys[i]
  1355. app := c.app.mountFields.appList[prefix]
  1356. if prefix == "" || strings.Contains(c.OriginalURL(), prefix) {
  1357. if len(layouts) == 0 && app.config.ViewsLayout != "" {
  1358. layouts = []string{
  1359. app.config.ViewsLayout,
  1360. }
  1361. }
  1362. // Render template from Views
  1363. if app.config.Views != nil {
  1364. if err := app.config.Views.Render(buf, name, bind, layouts...); err != nil {
  1365. return fmt.Errorf("failed to render: %w", err)
  1366. }
  1367. rendered = true
  1368. break
  1369. }
  1370. }
  1371. }
  1372. if !rendered {
  1373. // Render raw template using 'name' as filepath if no engine is set
  1374. var tmpl *template.Template
  1375. if _, err := readContent(buf, name); err != nil {
  1376. return err
  1377. }
  1378. // Parse template
  1379. tmpl, err := template.New("").Parse(c.app.getString(buf.Bytes()))
  1380. if err != nil {
  1381. return fmt.Errorf("failed to parse: %w", err)
  1382. }
  1383. buf.Reset()
  1384. // Render template
  1385. if err := tmpl.Execute(buf, bind); err != nil {
  1386. return fmt.Errorf("failed to execute: %w", err)
  1387. }
  1388. }
  1389. // Set Content-Type to text/html
  1390. c.fasthttp.Response.Header.SetContentType(MIMETextHTMLCharsetUTF8)
  1391. // Set rendered template to body
  1392. c.fasthttp.Response.SetBody(buf.Bytes())
  1393. return nil
  1394. }
  1395. func (c *Ctx) renderExtensions(bind interface{}) {
  1396. if bindMap, ok := bind.(Map); ok {
  1397. // Bind view map
  1398. c.viewBindMap.Range(func(key, value interface{}) bool {
  1399. keyValue, ok := key.(string)
  1400. if !ok {
  1401. return true
  1402. }
  1403. if _, ok := bindMap[keyValue]; !ok {
  1404. bindMap[keyValue] = value
  1405. }
  1406. return true
  1407. })
  1408. // Check if the PassLocalsToViews option is enabled (by default it is disabled)
  1409. if c.app.config.PassLocalsToViews {
  1410. // Loop through each local and set it in the map
  1411. c.fasthttp.VisitUserValues(func(key []byte, val interface{}) {
  1412. // check if bindMap doesn't contain the key
  1413. if _, ok := bindMap[c.app.getString(key)]; !ok {
  1414. // Set the key and value in the bindMap
  1415. bindMap[c.app.getString(key)] = val
  1416. }
  1417. })
  1418. }
  1419. }
  1420. if len(c.app.mountFields.appListKeys) == 0 {
  1421. c.app.generateAppListKeys()
  1422. }
  1423. }
  1424. // Route returns the matched Route struct.
  1425. func (c *Ctx) Route() *Route {
  1426. if c.route == nil {
  1427. // Fallback for fasthttp error handler
  1428. return &Route{
  1429. path: c.pathOriginal,
  1430. Path: c.pathOriginal,
  1431. Method: c.method,
  1432. Handlers: make([]Handler, 0),
  1433. Params: make([]string, 0),
  1434. }
  1435. }
  1436. return c.route
  1437. }
  1438. // SaveFile saves any multipart file to disk.
  1439. func (*Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error {
  1440. return fasthttp.SaveMultipartFile(fileheader, path)
  1441. }
  1442. // SaveFileToStorage saves any multipart file to an external storage system.
  1443. func (*Ctx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error {
  1444. file, err := fileheader.Open()
  1445. if err != nil {
  1446. return fmt.Errorf("failed to open: %w", err)
  1447. }
  1448. content, err := io.ReadAll(file)
  1449. if err != nil {
  1450. return fmt.Errorf("failed to read: %w", err)
  1451. }
  1452. if err := storage.Set(path, content, 0); err != nil {
  1453. return fmt.Errorf("failed to store: %w", err)
  1454. }
  1455. return nil
  1456. }
  1457. // Secure returns whether a secure connection was established.
  1458. func (c *Ctx) Secure() bool {
  1459. return c.Protocol() == schemeHTTPS
  1460. }
  1461. // Send sets the HTTP response body without copying it.
  1462. // From this point onward the body argument must not be changed.
  1463. func (c *Ctx) Send(body []byte) error {
  1464. // Write response body
  1465. c.fasthttp.Response.SetBodyRaw(body)
  1466. return nil
  1467. }
  1468. var (
  1469. sendFileOnce sync.Once
  1470. sendFileFS *fasthttp.FS
  1471. sendFileHandler fasthttp.RequestHandler
  1472. )
  1473. // SendFile transfers the file from the given path.
  1474. // The file is not compressed by default, enable this by passing a 'true' argument
  1475. // Sets the Content-Type response HTTP header field based on the filenames extension.
  1476. func (c *Ctx) SendFile(file string, compress ...bool) error {
  1477. // Save the filename, we will need it in the error message if the file isn't found
  1478. filename := file
  1479. // https://github.com/valyala/fasthttp/blob/c7576cc10cabfc9c993317a2d3f8355497bea156/fs.go#L129-L134
  1480. sendFileOnce.Do(func() {
  1481. const cacheDuration = 10 * time.Second
  1482. sendFileFS = &fasthttp.FS{
  1483. Root: "",
  1484. AllowEmptyRoot: true,
  1485. GenerateIndexPages: false,
  1486. AcceptByteRange: true,
  1487. Compress: true,
  1488. CompressedFileSuffix: c.app.config.CompressedFileSuffix,
  1489. CacheDuration: cacheDuration,
  1490. IndexNames: []string{"index.html"},
  1491. PathNotFound: func(ctx *fasthttp.RequestCtx) {
  1492. ctx.Response.SetStatusCode(StatusNotFound)
  1493. },
  1494. }
  1495. sendFileHandler = sendFileFS.NewRequestHandler()
  1496. })
  1497. // Keep original path for mutable params
  1498. c.pathOriginal = utils.CopyString(c.pathOriginal)
  1499. // Disable compression
  1500. if len(compress) == 0 || !compress[0] {
  1501. // https://github.com/valyala/fasthttp/blob/7cc6f4c513f9e0d3686142e0a1a5aa2f76b3194a/fs.go#L55
  1502. c.fasthttp.Request.Header.Del(HeaderAcceptEncoding)
  1503. }
  1504. // copy of https://github.com/valyala/fasthttp/blob/7cc6f4c513f9e0d3686142e0a1a5aa2f76b3194a/fs.go#L103-L121 with small adjustments
  1505. if len(file) == 0 || !filepath.IsAbs(file) {
  1506. // extend relative path to absolute path
  1507. hasTrailingSlash := len(file) > 0 && (file[len(file)-1] == '/' || file[len(file)-1] == '\\')
  1508. var err error
  1509. file = filepath.FromSlash(file)
  1510. if file, err = filepath.Abs(file); err != nil {
  1511. return fmt.Errorf("failed to determine abs file path: %w", err)
  1512. }
  1513. if hasTrailingSlash {
  1514. file += "/"
  1515. }
  1516. }
  1517. // convert the path to forward slashes regardless the OS in order to set the URI properly
  1518. // the handler will convert back to OS path separator before opening the file
  1519. file = filepath.ToSlash(file)
  1520. // Restore the original requested URL
  1521. originalURL := utils.CopyString(c.OriginalURL())
  1522. defer c.fasthttp.Request.SetRequestURI(originalURL)
  1523. // Set new URI for fileHandler
  1524. c.fasthttp.Request.SetRequestURI(file)
  1525. // Save status code
  1526. status := c.fasthttp.Response.StatusCode()
  1527. // Serve file
  1528. sendFileHandler(c.fasthttp)
  1529. // Get the status code which is set by fasthttp
  1530. fsStatus := c.fasthttp.Response.StatusCode()
  1531. // Set the status code set by the user if it is different from the fasthttp status code and 200
  1532. if status != fsStatus && status != StatusOK {
  1533. c.Status(status)
  1534. }
  1535. // Check for error
  1536. if status != StatusNotFound && fsStatus == StatusNotFound {
  1537. return NewError(StatusNotFound, fmt.Sprintf("sendfile: file %s not found", filename))
  1538. }
  1539. return nil
  1540. }
  1541. // SendStatus sets the HTTP status code and if the response body is empty,
  1542. // it sets the correct status message in the body.
  1543. func (c *Ctx) SendStatus(status int) error {
  1544. c.Status(status)
  1545. // Only set status body when there is no response body
  1546. if len(c.fasthttp.Response.Body()) == 0 {
  1547. return c.SendString(utils.StatusMessage(status))
  1548. }
  1549. return nil
  1550. }
  1551. // SendString sets the HTTP response body for string types.
  1552. // This means no type assertion, recommended for faster performance
  1553. func (c *Ctx) SendString(body string) error {
  1554. c.fasthttp.Response.SetBodyString(body)
  1555. return nil
  1556. }
  1557. // SendStream sets response body stream and optional body size.
  1558. func (c *Ctx) SendStream(stream io.Reader, size ...int) error {
  1559. if len(size) > 0 && size[0] >= 0 {
  1560. c.fasthttp.Response.SetBodyStream(stream, size[0])
  1561. } else {
  1562. c.fasthttp.Response.SetBodyStream(stream, -1)
  1563. }
  1564. return nil
  1565. }
  1566. // Set sets the response's HTTP header field to the specified key, value.
  1567. func (c *Ctx) Set(key, val string) {
  1568. c.fasthttp.Response.Header.Set(key, val)
  1569. }
  1570. func (c *Ctx) setCanonical(key, val string) {
  1571. c.fasthttp.Response.Header.SetCanonical(c.app.getBytes(key), c.app.getBytes(val))
  1572. }
  1573. // Subdomains returns a string slice of subdomains in the domain name of the request.
  1574. // The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.
  1575. func (c *Ctx) Subdomains(offset ...int) []string {
  1576. o := 2
  1577. if len(offset) > 0 {
  1578. o = offset[0]
  1579. }
  1580. subdomains := strings.Split(c.Hostname(), ".")
  1581. l := len(subdomains) - o
  1582. // Check index to avoid slice bounds out of range panic
  1583. if l < 0 {
  1584. l = len(subdomains)
  1585. }
  1586. subdomains = subdomains[:l]
  1587. return subdomains
  1588. }
  1589. // Stale is not implemented yet, pull requests are welcome!
  1590. func (c *Ctx) Stale() bool {
  1591. return !c.Fresh()
  1592. }
  1593. // Status sets the HTTP status for the response.
  1594. // This method is chainable.
  1595. func (c *Ctx) Status(status int) *Ctx {
  1596. c.fasthttp.Response.SetStatusCode(status)
  1597. return c
  1598. }
  1599. // String returns unique string representation of the ctx.
  1600. //
  1601. // The returned value may be useful for logging.
  1602. func (c *Ctx) String() string {
  1603. // Get buffer from pool
  1604. buf := bytebufferpool.Get()
  1605. // Start with the ID, converting it to a hex string without fmt.Sprintf
  1606. buf.WriteByte('#')
  1607. // Convert ID to hexadecimal
  1608. id := strconv.FormatUint(c.fasthttp.ID(), 16)
  1609. // Pad with leading zeros to ensure 16 characters
  1610. for i := 0; i < (16 - len(id)); i++ {
  1611. buf.WriteByte('0')
  1612. }
  1613. buf.WriteString(id)
  1614. buf.WriteString(" - ")
  1615. // Add local and remote addresses directly
  1616. buf.WriteString(c.fasthttp.LocalAddr().String())
  1617. buf.WriteString(" <-> ")
  1618. buf.WriteString(c.fasthttp.RemoteAddr().String())
  1619. buf.WriteString(" - ")
  1620. // Add method and URI
  1621. buf.Write(c.fasthttp.Request.Header.Method())
  1622. buf.WriteByte(' ')
  1623. buf.Write(c.fasthttp.URI().FullURI())
  1624. // Allocate string
  1625. str := buf.String()
  1626. // Reset buffer
  1627. buf.Reset()
  1628. bytebufferpool.Put(buf)
  1629. return str
  1630. }
  1631. // Type sets the Content-Type HTTP header to the MIME type specified by the file extension.
  1632. func (c *Ctx) Type(extension string, charset ...string) *Ctx {
  1633. if len(charset) > 0 {
  1634. c.fasthttp.Response.Header.SetContentType(utils.GetMIME(extension) + "; charset=" + charset[0])
  1635. } else {
  1636. c.fasthttp.Response.Header.SetContentType(utils.GetMIME(extension))
  1637. }
  1638. return c
  1639. }
  1640. // Vary adds the given header field to the Vary response header.
  1641. // This will append the header, if not already listed, otherwise leaves it listed in the current location.
  1642. func (c *Ctx) Vary(fields ...string) {
  1643. c.Append(HeaderVary, fields...)
  1644. }
  1645. // Write appends p into response body.
  1646. func (c *Ctx) Write(p []byte) (int, error) {
  1647. c.fasthttp.Response.AppendBody(p)
  1648. return len(p), nil
  1649. }
  1650. // Writef appends f & a into response body writer.
  1651. func (c *Ctx) Writef(f string, a ...interface{}) (int, error) {
  1652. //nolint:wrapcheck // This must not be wrapped
  1653. return fmt.Fprintf(c.fasthttp.Response.BodyWriter(), f, a...)
  1654. }
  1655. // WriteString appends s to response body.
  1656. func (c *Ctx) WriteString(s string) (int, error) {
  1657. c.fasthttp.Response.AppendBodyString(s)
  1658. return len(s), nil
  1659. }
  1660. // XHR returns a Boolean property, that is true, if the request's X-Requested-With header field is XMLHttpRequest,
  1661. // indicating that the request was issued by a client library (such as jQuery).
  1662. func (c *Ctx) XHR() bool {
  1663. return utils.EqualFoldBytes(c.app.getBytes(c.Get(HeaderXRequestedWith)), []byte("xmlhttprequest"))
  1664. }
  1665. // configDependentPaths set paths for route recognition and prepared paths for the user,
  1666. // here the features for caseSensitive, decoded paths, strict paths are evaluated
  1667. func (c *Ctx) configDependentPaths() {
  1668. c.pathBuffer = append(c.pathBuffer[0:0], c.pathOriginal...)
  1669. // If UnescapePath enabled, we decode the path and save it for the framework user
  1670. if c.app.config.UnescapePath {
  1671. c.pathBuffer = fasthttp.AppendUnquotedArg(c.pathBuffer[:0], c.pathBuffer)
  1672. }
  1673. c.path = c.app.getString(c.pathBuffer)
  1674. // another path is specified which is for routing recognition only
  1675. // use the path that was changed by the previous configuration flags
  1676. c.detectionPathBuffer = append(c.detectionPathBuffer[0:0], c.pathBuffer...)
  1677. // If CaseSensitive is disabled, we lowercase the original path
  1678. if !c.app.config.CaseSensitive {
  1679. c.detectionPathBuffer = utils.ToLowerBytes(c.detectionPathBuffer)
  1680. }
  1681. // If StrictRouting is disabled, we strip all trailing slashes
  1682. if !c.app.config.StrictRouting && len(c.detectionPathBuffer) > 1 && c.detectionPathBuffer[len(c.detectionPathBuffer)-1] == '/' {
  1683. c.detectionPathBuffer = utils.TrimRightBytes(c.detectionPathBuffer, '/')
  1684. }
  1685. c.detectionPath = c.app.getString(c.detectionPathBuffer)
  1686. // Define the path for dividing routes into areas for fast tree detection, so that fewer routes need to be traversed,
  1687. // since the first three characters area select a list of routes
  1688. c.treePath = c.treePath[0:0]
  1689. const maxDetectionPaths = 3
  1690. if len(c.detectionPath) >= maxDetectionPaths {
  1691. c.treePath = c.detectionPath[:maxDetectionPaths]
  1692. }
  1693. }
  1694. func (c *Ctx) IsProxyTrusted() bool {
  1695. if !c.app.config.EnableTrustedProxyCheck {
  1696. return true
  1697. }
  1698. ip := c.fasthttp.RemoteIP()
  1699. if _, trusted := c.app.config.trustedProxiesMap[ip.String()]; trusted {
  1700. return true
  1701. }
  1702. for _, ipNet := range c.app.config.trustedProxyRanges {
  1703. if ipNet.Contains(ip) {
  1704. return true
  1705. }
  1706. }
  1707. return false
  1708. }
  1709. var localHosts = [...]string{"127.0.0.1", "::1"}
  1710. // IsLocalHost will return true if address is a localhost address.
  1711. func (*Ctx) isLocalHost(address string) bool {
  1712. for _, h := range localHosts {
  1713. if address == h {
  1714. return true
  1715. }
  1716. }
  1717. return false
  1718. }
  1719. // IsFromLocal will return true if request came from local.
  1720. func (c *Ctx) IsFromLocal() bool {
  1721. return c.isLocalHost(c.fasthttp.RemoteIP().String())
  1722. }
  1723. func (c *Ctx) getBody() []byte {
  1724. if c.app.config.Immutable {
  1725. return utils.CopyBytes(c.fasthttp.Request.Body())
  1726. }
  1727. return c.fasthttp.Request.Body()
  1728. }