ctx.go 60 KB

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