ctx.go 57 KB

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