ctx.go 60 KB

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