ctx.go 60 KB

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