ctx.go 59 KB

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