ctx.go 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993
  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. //
  843. // All the values are removed from ctx after returning from the top
  844. // RequestHandler. Additionally, Close method is called on each value
  845. // implementing io.Closer before removing the value from ctx.
  846. func (c *Ctx) Locals(key interface{}, value ...interface{}) interface{} {
  847. if len(value) == 0 {
  848. return c.fasthttp.UserValue(key)
  849. }
  850. c.fasthttp.SetUserValue(key, value[0])
  851. return value[0]
  852. }
  853. // Location sets the response Location HTTP header to the specified path parameter.
  854. func (c *Ctx) Location(path string) {
  855. c.setCanonical(HeaderLocation, path)
  856. }
  857. // Method returns the HTTP request method for the context, optionally overridden by the provided argument.
  858. // If no override is given or if the provided override is not a valid HTTP method, it returns the current method from the context.
  859. // Otherwise, it updates the context's method and returns the overridden method as a string.
  860. func (c *Ctx) Method(override ...string) string {
  861. if len(override) == 0 {
  862. // Nothing to override, just return current method from context
  863. return c.method
  864. }
  865. method := utils.ToUpper(override[0])
  866. mINT := c.app.methodInt(method)
  867. if mINT == -1 {
  868. // Provided override does not valid HTTP method, no override, return current method
  869. return c.method
  870. }
  871. c.method = method
  872. c.methodINT = mINT
  873. return c.method
  874. }
  875. // MultipartForm parse form entries from binary.
  876. // This returns a map[string][]string, so given a key the value will be a string slice.
  877. func (c *Ctx) MultipartForm() (*multipart.Form, error) {
  878. return c.fasthttp.MultipartForm()
  879. }
  880. // ClientHelloInfo return CHI from context
  881. func (c *Ctx) ClientHelloInfo() *tls.ClientHelloInfo {
  882. if c.app.tlsHandler != nil {
  883. return c.app.tlsHandler.clientHelloInfo
  884. }
  885. return nil
  886. }
  887. // Next executes the next method in the stack that matches the current route.
  888. func (c *Ctx) Next() error {
  889. // Increment handler index
  890. c.indexHandler++
  891. var err error
  892. // Did we execute all route handlers?
  893. if c.indexHandler < len(c.route.Handlers) {
  894. // Continue route stack
  895. err = c.route.Handlers[c.indexHandler](c)
  896. } else {
  897. // Continue handler stack
  898. _, err = c.app.next(c)
  899. }
  900. return err
  901. }
  902. // RestartRouting instead of going to the next handler. This may be useful after
  903. // changing the request path. Note that handlers might be executed again.
  904. func (c *Ctx) RestartRouting() error {
  905. c.indexRoute = -1
  906. _, err := c.app.next(c)
  907. return err
  908. }
  909. // OriginalURL contains the original request URL.
  910. // Returned value is only valid within the handler. Do not store any references.
  911. // Make copies or use the Immutable setting to use the value outside the Handler.
  912. func (c *Ctx) OriginalURL() string {
  913. return c.app.getString(c.fasthttp.Request.Header.RequestURI())
  914. }
  915. // Params is used to get the route parameters.
  916. // Defaults to empty string "" if the param doesn't exist.
  917. // If a default value is given, it will return that value if the param doesn't exist.
  918. // Returned value is only valid within the handler. Do not store any references.
  919. // Make copies or use the Immutable setting to use the value outside the Handler.
  920. func (c *Ctx) Params(key string, defaultValue ...string) string {
  921. if key == "*" || key == "+" {
  922. key += "1"
  923. }
  924. for i := range c.route.Params {
  925. if len(key) != len(c.route.Params[i]) {
  926. continue
  927. }
  928. if c.route.Params[i] == key || (!c.app.config.CaseSensitive && utils.EqualFold(c.route.Params[i], key)) {
  929. // in case values are not here
  930. if len(c.values) <= i || len(c.values[i]) == 0 {
  931. break
  932. }
  933. return c.values[i]
  934. }
  935. }
  936. return defaultString("", defaultValue)
  937. }
  938. // AllParams Params is used to get all route parameters.
  939. // Using Params method to get params.
  940. func (c *Ctx) AllParams() map[string]string {
  941. params := make(map[string]string, len(c.route.Params))
  942. for _, param := range c.route.Params {
  943. params[param] = c.Params(param)
  944. }
  945. return params
  946. }
  947. // ParamsParser binds the param string to a struct.
  948. func (c *Ctx) ParamsParser(out interface{}) error {
  949. params := make(map[string][]string, len(c.route.Params))
  950. for _, param := range c.route.Params {
  951. params[param] = append(params[param], c.Params(param))
  952. }
  953. return c.parseToStruct(paramsTag, out, params)
  954. }
  955. // ParamsInt is used to get an integer from the route parameters
  956. // it defaults to zero if the parameter is not found or if the
  957. // parameter cannot be converted to an integer
  958. // If a default value is given, it will return that value in case the param
  959. // doesn't exist or cannot be converted to an integer
  960. func (c *Ctx) ParamsInt(key string, defaultValue ...int) (int, error) {
  961. // Use Atoi to convert the param to an int or return zero and an error
  962. value, err := strconv.Atoi(c.Params(key))
  963. if err != nil {
  964. if len(defaultValue) > 0 {
  965. return defaultValue[0], nil
  966. }
  967. return 0, fmt.Errorf("failed to convert: %w", err)
  968. }
  969. return value, nil
  970. }
  971. // Path returns the path part of the request URL.
  972. // Optionally, you could override the path.
  973. func (c *Ctx) Path(override ...string) string {
  974. if len(override) != 0 && c.path != override[0] {
  975. // Set new path to context
  976. c.pathOriginal = override[0]
  977. // Set new path to request context
  978. c.fasthttp.Request.URI().SetPath(c.pathOriginal)
  979. // Prettify path
  980. c.configDependentPaths()
  981. }
  982. return c.path
  983. }
  984. // Protocol contains the request protocol string: http or https for TLS requests.
  985. // Please use Config.EnableTrustedProxyCheck to prevent header spoofing, in case when your app is behind the proxy.
  986. func (c *Ctx) Protocol() string {
  987. if c.fasthttp.IsTLS() {
  988. return schemeHTTPS
  989. }
  990. if !c.IsProxyTrusted() {
  991. return schemeHTTP
  992. }
  993. scheme := schemeHTTP
  994. const lenXHeaderName = 12
  995. c.fasthttp.Request.Header.VisitAll(func(key, val []byte) {
  996. if len(key) < lenXHeaderName {
  997. return // Neither "X-Forwarded-" nor "X-Url-Scheme"
  998. }
  999. switch {
  1000. case bytes.HasPrefix(key, []byte("X-Forwarded-")):
  1001. if bytes.Equal(key, []byte(HeaderXForwardedProto)) ||
  1002. bytes.Equal(key, []byte(HeaderXForwardedProtocol)) {
  1003. v := c.app.getString(val)
  1004. commaPos := strings.Index(v, ",")
  1005. if commaPos != -1 {
  1006. scheme = v[:commaPos]
  1007. } else {
  1008. scheme = v
  1009. }
  1010. } else if bytes.Equal(key, []byte(HeaderXForwardedSsl)) && bytes.Equal(val, []byte("on")) {
  1011. scheme = schemeHTTPS
  1012. }
  1013. case bytes.Equal(key, []byte(HeaderXUrlScheme)):
  1014. scheme = c.app.getString(val)
  1015. }
  1016. })
  1017. return scheme
  1018. }
  1019. // Query returns the query string parameter in the url.
  1020. // Defaults to empty string "" if the query doesn't exist.
  1021. // If a default value is given, it will return that value if the query doesn't exist.
  1022. // Returned value is only valid within the handler. Do not store any references.
  1023. // Make copies or use the Immutable setting to use the value outside the Handler.
  1024. func (c *Ctx) Query(key string, defaultValue ...string) string {
  1025. return defaultString(c.app.getString(c.fasthttp.QueryArgs().Peek(key)), defaultValue)
  1026. }
  1027. // Queries returns a map of query parameters and their values.
  1028. //
  1029. // GET /?name=alex&wanna_cake=2&id=
  1030. // Queries()["name"] == "alex"
  1031. // Queries()["wanna_cake"] == "2"
  1032. // Queries()["id"] == ""
  1033. //
  1034. // GET /?field1=value1&field1=value2&field2=value3
  1035. // Queries()["field1"] == "value2"
  1036. // Queries()["field2"] == "value3"
  1037. //
  1038. // GET /?list_a=1&list_a=2&list_a=3&list_b[]=1&list_b[]=2&list_b[]=3&list_c=1,2,3
  1039. // Queries()["list_a"] == "3"
  1040. // Queries()["list_b[]"] == "3"
  1041. // Queries()["list_c"] == "1,2,3"
  1042. //
  1043. // GET /api/search?filters.author.name=John&filters.category.name=Technology&filters[customer][name]=Alice&filters[status]=pending
  1044. // Queries()["filters.author.name"] == "John"
  1045. // Queries()["filters.category.name"] == "Technology"
  1046. // Queries()["filters[customer][name]"] == "Alice"
  1047. // Queries()["filters[status]"] == "pending"
  1048. func (c *Ctx) Queries() map[string]string {
  1049. m := make(map[string]string, c.Context().QueryArgs().Len())
  1050. c.Context().QueryArgs().VisitAll(func(key, value []byte) {
  1051. m[c.app.getString(key)] = c.app.getString(value)
  1052. })
  1053. return m
  1054. }
  1055. // QueryInt returns integer value of key string parameter in the url.
  1056. // Default to empty or invalid key is 0.
  1057. //
  1058. // GET /?name=alex&wanna_cake=2&id=
  1059. // QueryInt("wanna_cake", 1) == 2
  1060. // QueryInt("name", 1) == 1
  1061. // QueryInt("id", 1) == 1
  1062. // QueryInt("id") == 0
  1063. func (c *Ctx) QueryInt(key string, defaultValue ...int) int {
  1064. // Use Atoi to convert the param to an int or return zero and an error
  1065. value, err := strconv.Atoi(c.app.getString(c.fasthttp.QueryArgs().Peek(key)))
  1066. if err != nil {
  1067. if len(defaultValue) > 0 {
  1068. return defaultValue[0]
  1069. }
  1070. return 0
  1071. }
  1072. return value
  1073. }
  1074. // QueryBool returns bool value of key string parameter in the url.
  1075. // Default to empty or invalid key is false.
  1076. //
  1077. // Get /?name=alex&want_pizza=false&id=
  1078. // QueryBool("want_pizza") == false
  1079. // QueryBool("want_pizza", true) == false
  1080. // QueryBool("name") == false
  1081. // QueryBool("name", true) == true
  1082. // QueryBool("id") == false
  1083. // QueryBool("id", true) == true
  1084. func (c *Ctx) QueryBool(key string, defaultValue ...bool) bool {
  1085. value, err := strconv.ParseBool(c.app.getString(c.fasthttp.QueryArgs().Peek(key)))
  1086. if err != nil {
  1087. if len(defaultValue) > 0 {
  1088. return defaultValue[0]
  1089. }
  1090. return false
  1091. }
  1092. return value
  1093. }
  1094. // QueryFloat returns float64 value of key string parameter in the url.
  1095. // Default to empty or invalid key is 0.
  1096. //
  1097. // GET /?name=alex&amount=32.23&id=
  1098. // QueryFloat("amount") = 32.23
  1099. // QueryFloat("amount", 3) = 32.23
  1100. // QueryFloat("name", 1) = 1
  1101. // QueryFloat("name") = 0
  1102. // QueryFloat("id", 3) = 3
  1103. func (c *Ctx) QueryFloat(key string, defaultValue ...float64) float64 {
  1104. // use strconv.ParseFloat to convert the param to a float or return zero and an error.
  1105. value, err := strconv.ParseFloat(c.app.getString(c.fasthttp.QueryArgs().Peek(key)), 64)
  1106. if err != nil {
  1107. if len(defaultValue) > 0 {
  1108. return defaultValue[0]
  1109. }
  1110. return 0
  1111. }
  1112. return value
  1113. }
  1114. // QueryParser binds the query string to a struct.
  1115. func (c *Ctx) QueryParser(out interface{}) error {
  1116. data := make(map[string][]string)
  1117. var err error
  1118. c.fasthttp.QueryArgs().VisitAll(func(key, val []byte) {
  1119. if err != nil {
  1120. return
  1121. }
  1122. k := c.app.getString(key)
  1123. v := c.app.getString(val)
  1124. if strings.Contains(k, "[") {
  1125. k, err = parseParamSquareBrackets(k)
  1126. }
  1127. if c.app.config.EnableSplittingOnParsers && strings.Contains(v, ",") && equalFieldType(out, reflect.Slice, k, queryTag) {
  1128. values := strings.Split(v, ",")
  1129. for i := 0; i < len(values); i++ {
  1130. data[k] = append(data[k], values[i])
  1131. }
  1132. } else {
  1133. data[k] = append(data[k], v)
  1134. }
  1135. })
  1136. if err != nil {
  1137. return err
  1138. }
  1139. return c.parseToStruct(queryTag, out, data)
  1140. }
  1141. func parseParamSquareBrackets(k string) (string, error) {
  1142. bb := bytebufferpool.Get()
  1143. defer bytebufferpool.Put(bb)
  1144. kbytes := []byte(k)
  1145. for i, b := range kbytes {
  1146. if b == '[' && kbytes[i+1] != ']' {
  1147. if err := bb.WriteByte('.'); err != nil {
  1148. return "", fmt.Errorf("failed to write: %w", err)
  1149. }
  1150. }
  1151. if b == '[' || b == ']' {
  1152. continue
  1153. }
  1154. if err := bb.WriteByte(b); err != nil {
  1155. return "", fmt.Errorf("failed to write: %w", err)
  1156. }
  1157. }
  1158. return bb.String(), nil
  1159. }
  1160. // ReqHeaderParser binds the request header strings to a struct.
  1161. func (c *Ctx) ReqHeaderParser(out interface{}) error {
  1162. data := make(map[string][]string)
  1163. c.fasthttp.Request.Header.VisitAll(func(key, val []byte) {
  1164. k := c.app.getString(key)
  1165. v := c.app.getString(val)
  1166. if c.app.config.EnableSplittingOnParsers && strings.Contains(v, ",") && equalFieldType(out, reflect.Slice, k, reqHeaderTag) {
  1167. values := strings.Split(v, ",")
  1168. for i := 0; i < len(values); i++ {
  1169. data[k] = append(data[k], values[i])
  1170. }
  1171. } else {
  1172. data[k] = append(data[k], v)
  1173. }
  1174. })
  1175. return c.parseToStruct(reqHeaderTag, out, data)
  1176. }
  1177. func (*Ctx) parseToStruct(aliasTag string, out interface{}, data map[string][]string) error {
  1178. // Get decoder from pool
  1179. schemaDecoder, ok := decoderPoolMap[aliasTag].Get().(*schema.Decoder)
  1180. if !ok {
  1181. panic(fmt.Errorf("failed to type-assert to *schema.Decoder"))
  1182. }
  1183. defer decoderPoolMap[aliasTag].Put(schemaDecoder)
  1184. // Set alias tag
  1185. schemaDecoder.SetAliasTag(aliasTag)
  1186. if err := schemaDecoder.Decode(out, data); err != nil {
  1187. return fmt.Errorf("failed to decode: %w", err)
  1188. }
  1189. return nil
  1190. }
  1191. func equalFieldType(out interface{}, kind reflect.Kind, key, tag string) bool {
  1192. // Get type of interface
  1193. outTyp := reflect.TypeOf(out).Elem()
  1194. key = utils.ToLower(key)
  1195. // Must be a struct to match a field
  1196. if outTyp.Kind() != reflect.Struct {
  1197. return false
  1198. }
  1199. // Copy interface to an value to be used
  1200. outVal := reflect.ValueOf(out).Elem()
  1201. // Loop over each field
  1202. for i := 0; i < outTyp.NumField(); i++ {
  1203. // Get field value data
  1204. structField := outVal.Field(i)
  1205. // Can this field be changed?
  1206. if !structField.CanSet() {
  1207. continue
  1208. }
  1209. // Get field key data
  1210. typeField := outTyp.Field(i)
  1211. // Get type of field key
  1212. structFieldKind := structField.Kind()
  1213. // Does the field type equals input?
  1214. if structFieldKind != kind {
  1215. continue
  1216. }
  1217. // Get tag from field if exist
  1218. inputFieldName := typeField.Tag.Get(tag)
  1219. if inputFieldName == "" {
  1220. inputFieldName = typeField.Name
  1221. } else {
  1222. inputFieldName = strings.Split(inputFieldName, ",")[0]
  1223. }
  1224. // Compare field/tag with provided key
  1225. if utils.ToLower(inputFieldName) == key {
  1226. return true
  1227. }
  1228. }
  1229. return false
  1230. }
  1231. var (
  1232. ErrRangeMalformed = errors.New("range: malformed range header string")
  1233. ErrRangeUnsatisfiable = errors.New("range: unsatisfiable range")
  1234. )
  1235. // Range returns a struct containing the type and a slice of ranges.
  1236. func (c *Ctx) Range(size int) (Range, error) {
  1237. var (
  1238. rangeData Range
  1239. ranges string
  1240. )
  1241. rangeStr := c.Get(HeaderRange)
  1242. i := strings.IndexByte(rangeStr, '=')
  1243. if i == -1 || strings.Contains(rangeStr[i+1:], "=") {
  1244. return rangeData, ErrRangeMalformed
  1245. }
  1246. rangeData.Type = rangeStr[:i]
  1247. ranges = rangeStr[i+1:]
  1248. var (
  1249. singleRange string
  1250. moreRanges = ranges
  1251. )
  1252. for moreRanges != "" {
  1253. singleRange = moreRanges
  1254. if i := strings.IndexByte(moreRanges, ','); i >= 0 {
  1255. singleRange = moreRanges[:i]
  1256. moreRanges = moreRanges[i+1:]
  1257. } else {
  1258. moreRanges = ""
  1259. }
  1260. var (
  1261. startStr, endStr string
  1262. i int
  1263. )
  1264. if i = strings.IndexByte(singleRange, '-'); i == -1 {
  1265. return rangeData, ErrRangeMalformed
  1266. }
  1267. startStr = singleRange[:i]
  1268. endStr = singleRange[i+1:]
  1269. start, startErr := fasthttp.ParseUint(utils.UnsafeBytes(startStr))
  1270. end, endErr := fasthttp.ParseUint(utils.UnsafeBytes(endStr))
  1271. if startErr != nil { // -nnn
  1272. start = size - end
  1273. end = size - 1
  1274. } else if endErr != nil { // nnn-
  1275. end = size - 1
  1276. }
  1277. if end > size-1 { // limit last-byte-pos to current length
  1278. end = size - 1
  1279. }
  1280. if start > end || start < 0 {
  1281. continue
  1282. }
  1283. rangeData.Ranges = append(rangeData.Ranges, struct {
  1284. Start int
  1285. End int
  1286. }{
  1287. start,
  1288. end,
  1289. })
  1290. }
  1291. if len(rangeData.Ranges) < 1 {
  1292. return rangeData, ErrRangeUnsatisfiable
  1293. }
  1294. return rangeData, nil
  1295. }
  1296. // Redirect to the URL derived from the specified path, with specified status.
  1297. // If status is not specified, status defaults to 302 Found.
  1298. func (c *Ctx) Redirect(location string, status ...int) error {
  1299. c.setCanonical(HeaderLocation, location)
  1300. if len(status) > 0 {
  1301. c.Status(status[0])
  1302. } else {
  1303. c.Status(StatusFound)
  1304. }
  1305. return nil
  1306. }
  1307. // Bind Add vars to default view var map binding to template engine.
  1308. // Variables are read by the Render method and may be overwritten.
  1309. func (c *Ctx) Bind(vars Map) error {
  1310. // init viewBindMap - lazy map
  1311. for k, v := range vars {
  1312. c.viewBindMap.Store(k, v)
  1313. }
  1314. return nil
  1315. }
  1316. // getLocationFromRoute get URL location from route using parameters
  1317. func (c *Ctx) getLocationFromRoute(route Route, params Map) (string, error) {
  1318. buf := bytebufferpool.Get()
  1319. for _, segment := range route.routeParser.segs {
  1320. if !segment.IsParam {
  1321. _, err := buf.WriteString(segment.Const)
  1322. if err != nil {
  1323. return "", fmt.Errorf("failed to write string: %w", err)
  1324. }
  1325. continue
  1326. }
  1327. for key, val := range params {
  1328. isSame := key == segment.ParamName || (!c.app.config.CaseSensitive && utils.EqualFold(key, segment.ParamName))
  1329. isGreedy := segment.IsGreedy && len(key) == 1 && isInCharset(key[0], greedyParameters)
  1330. if isSame || isGreedy {
  1331. _, err := buf.WriteString(utils.ToString(val))
  1332. if err != nil {
  1333. return "", fmt.Errorf("failed to write string: %w", err)
  1334. }
  1335. }
  1336. }
  1337. }
  1338. location := buf.String()
  1339. // release buffer
  1340. bytebufferpool.Put(buf)
  1341. return location, nil
  1342. }
  1343. // GetRouteURL generates URLs to named routes, with parameters. URLs are relative, for example: "/user/1831"
  1344. func (c *Ctx) GetRouteURL(routeName string, params Map) (string, error) {
  1345. return c.getLocationFromRoute(c.App().GetRoute(routeName), params)
  1346. }
  1347. // RedirectToRoute to the Route registered in the app with appropriate parameters
  1348. // If status is not specified, status defaults to 302 Found.
  1349. // If you want to send queries to route, you must add "queries" key typed as map[string]string to params.
  1350. func (c *Ctx) RedirectToRoute(routeName string, params Map, status ...int) error {
  1351. location, err := c.getLocationFromRoute(c.App().GetRoute(routeName), params)
  1352. if err != nil {
  1353. return err
  1354. }
  1355. // Check queries
  1356. if queries, ok := params["queries"].(map[string]string); ok {
  1357. queryText := bytebufferpool.Get()
  1358. defer bytebufferpool.Put(queryText)
  1359. i := 1
  1360. for k, v := range queries {
  1361. _, _ = queryText.WriteString(k + "=" + v) //nolint:errcheck // This will never fail
  1362. if i != len(queries) {
  1363. _, _ = queryText.WriteString("&") //nolint:errcheck // This will never fail
  1364. }
  1365. i++
  1366. }
  1367. return c.Redirect(location+"?"+queryText.String(), status...)
  1368. }
  1369. return c.Redirect(location, status...)
  1370. }
  1371. // RedirectBack to the URL to referer
  1372. // If status is not specified, status defaults to 302 Found.
  1373. func (c *Ctx) RedirectBack(fallback string, status ...int) error {
  1374. location := c.Get(HeaderReferer)
  1375. if location == "" {
  1376. location = fallback
  1377. }
  1378. return c.Redirect(location, status...)
  1379. }
  1380. // Render a template with data and sends a text/html response.
  1381. // We support the following engines: html, amber, handlebars, mustache, pug
  1382. func (c *Ctx) Render(name string, bind interface{}, layouts ...string) error {
  1383. // Get new buffer from pool
  1384. buf := bytebufferpool.Get()
  1385. defer bytebufferpool.Put(buf)
  1386. // Initialize empty bind map if bind is nil
  1387. if bind == nil {
  1388. bind = make(Map)
  1389. }
  1390. // Pass-locals-to-views, bind, appListKeys
  1391. c.renderExtensions(bind)
  1392. var rendered bool
  1393. for i := len(c.app.mountFields.appListKeys) - 1; i >= 0; i-- {
  1394. prefix := c.app.mountFields.appListKeys[i]
  1395. app := c.app.mountFields.appList[prefix]
  1396. if prefix == "" || strings.Contains(c.OriginalURL(), prefix) {
  1397. if len(layouts) == 0 && app.config.ViewsLayout != "" {
  1398. layouts = []string{
  1399. app.config.ViewsLayout,
  1400. }
  1401. }
  1402. // Render template from Views
  1403. if app.config.Views != nil {
  1404. if err := app.config.Views.Render(buf, name, bind, layouts...); err != nil {
  1405. return fmt.Errorf("failed to render: %w", err)
  1406. }
  1407. rendered = true
  1408. break
  1409. }
  1410. }
  1411. }
  1412. if !rendered {
  1413. // Render raw template using 'name' as filepath if no engine is set
  1414. var tmpl *template.Template
  1415. if _, err := readContent(buf, name); err != nil {
  1416. return err
  1417. }
  1418. // Parse template
  1419. tmpl, err := template.New("").Parse(c.app.getString(buf.Bytes()))
  1420. if err != nil {
  1421. return fmt.Errorf("failed to parse: %w", err)
  1422. }
  1423. buf.Reset()
  1424. // Render template
  1425. if err := tmpl.Execute(buf, bind); err != nil {
  1426. return fmt.Errorf("failed to execute: %w", err)
  1427. }
  1428. }
  1429. // Set Content-Type to text/html
  1430. c.fasthttp.Response.Header.SetContentType(MIMETextHTMLCharsetUTF8)
  1431. // Set rendered template to body
  1432. c.fasthttp.Response.SetBody(buf.Bytes())
  1433. return nil
  1434. }
  1435. func (c *Ctx) renderExtensions(bind interface{}) {
  1436. if bindMap, ok := bind.(Map); ok {
  1437. // Bind view map
  1438. c.viewBindMap.Range(func(key, value interface{}) bool {
  1439. keyValue, ok := key.(string)
  1440. if !ok {
  1441. return true
  1442. }
  1443. if _, ok := bindMap[keyValue]; !ok {
  1444. bindMap[keyValue] = value
  1445. }
  1446. return true
  1447. })
  1448. // Check if the PassLocalsToViews option is enabled (by default it is disabled)
  1449. if c.app.config.PassLocalsToViews {
  1450. // Loop through each local and set it in the map
  1451. c.fasthttp.VisitUserValues(func(key []byte, val interface{}) {
  1452. // check if bindMap doesn't contain the key
  1453. if _, ok := bindMap[c.app.getString(key)]; !ok {
  1454. // Set the key and value in the bindMap
  1455. bindMap[c.app.getString(key)] = val
  1456. }
  1457. })
  1458. }
  1459. }
  1460. if len(c.app.mountFields.appListKeys) == 0 {
  1461. c.app.generateAppListKeys()
  1462. }
  1463. }
  1464. // Route returns the matched Route struct.
  1465. func (c *Ctx) Route() *Route {
  1466. if c.route == nil {
  1467. // Fallback for fasthttp error handler
  1468. return &Route{
  1469. path: c.pathOriginal,
  1470. Path: c.pathOriginal,
  1471. Method: c.method,
  1472. Handlers: make([]Handler, 0),
  1473. Params: make([]string, 0),
  1474. }
  1475. }
  1476. return c.route
  1477. }
  1478. // SaveFile saves any multipart file to disk.
  1479. func (*Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error {
  1480. return fasthttp.SaveMultipartFile(fileheader, path)
  1481. }
  1482. // SaveFileToStorage saves any multipart file to an external storage system.
  1483. func (*Ctx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error {
  1484. file, err := fileheader.Open()
  1485. if err != nil {
  1486. return fmt.Errorf("failed to open: %w", err)
  1487. }
  1488. content, err := io.ReadAll(file)
  1489. if err != nil {
  1490. return fmt.Errorf("failed to read: %w", err)
  1491. }
  1492. if err := storage.Set(path, content, 0); err != nil {
  1493. return fmt.Errorf("failed to store: %w", err)
  1494. }
  1495. return nil
  1496. }
  1497. // Secure returns whether a secure connection was established.
  1498. func (c *Ctx) Secure() bool {
  1499. return c.Protocol() == schemeHTTPS
  1500. }
  1501. // Send sets the HTTP response body without copying it.
  1502. // From this point onward the body argument must not be changed.
  1503. func (c *Ctx) Send(body []byte) error {
  1504. // Write response body
  1505. c.fasthttp.Response.SetBodyRaw(body)
  1506. return nil
  1507. }
  1508. var (
  1509. sendFileOnce sync.Once
  1510. sendFileFS *fasthttp.FS
  1511. sendFileHandler fasthttp.RequestHandler
  1512. )
  1513. // SendFile transfers the file from the given path.
  1514. // The file is not compressed by default, enable this by passing a 'true' argument
  1515. // Sets the Content-Type response HTTP header field based on the filenames extension.
  1516. func (c *Ctx) SendFile(file string, compress ...bool) error {
  1517. // Save the filename, we will need it in the error message if the file isn't found
  1518. filename := file
  1519. // https://github.com/valyala/fasthttp/blob/c7576cc10cabfc9c993317a2d3f8355497bea156/fs.go#L129-L134
  1520. sendFileOnce.Do(func() {
  1521. const cacheDuration = 10 * time.Second
  1522. sendFileFS = &fasthttp.FS{
  1523. Root: "",
  1524. AllowEmptyRoot: true,
  1525. GenerateIndexPages: false,
  1526. AcceptByteRange: true,
  1527. Compress: true,
  1528. CompressedFileSuffix: c.app.config.CompressedFileSuffix,
  1529. CacheDuration: cacheDuration,
  1530. IndexNames: []string{"index.html"},
  1531. PathNotFound: func(ctx *fasthttp.RequestCtx) {
  1532. ctx.Response.SetStatusCode(StatusNotFound)
  1533. },
  1534. }
  1535. sendFileHandler = sendFileFS.NewRequestHandler()
  1536. })
  1537. // Keep original path for mutable params
  1538. c.pathOriginal = utils.CopyString(c.pathOriginal)
  1539. // Disable compression
  1540. if len(compress) == 0 || !compress[0] {
  1541. // https://github.com/valyala/fasthttp/blob/7cc6f4c513f9e0d3686142e0a1a5aa2f76b3194a/fs.go#L55
  1542. c.fasthttp.Request.Header.Del(HeaderAcceptEncoding)
  1543. }
  1544. // copy of https://github.com/valyala/fasthttp/blob/7cc6f4c513f9e0d3686142e0a1a5aa2f76b3194a/fs.go#L103-L121 with small adjustments
  1545. if len(file) == 0 || !filepath.IsAbs(file) {
  1546. // extend relative path to absolute path
  1547. hasTrailingSlash := len(file) > 0 && (file[len(file)-1] == '/' || file[len(file)-1] == '\\')
  1548. var err error
  1549. file = filepath.FromSlash(file)
  1550. if file, err = filepath.Abs(file); err != nil {
  1551. return fmt.Errorf("failed to determine abs file path: %w", err)
  1552. }
  1553. if hasTrailingSlash {
  1554. file += "/"
  1555. }
  1556. }
  1557. // convert the path to forward slashes regardless the OS in order to set the URI properly
  1558. // the handler will convert back to OS path separator before opening the file
  1559. file = filepath.ToSlash(file)
  1560. // Restore the original requested URL
  1561. originalURL := utils.CopyString(c.OriginalURL())
  1562. defer c.fasthttp.Request.SetRequestURI(originalURL)
  1563. // Set new URI for fileHandler
  1564. c.fasthttp.Request.SetRequestURI(file)
  1565. // Save status code
  1566. status := c.fasthttp.Response.StatusCode()
  1567. // Serve file
  1568. sendFileHandler(c.fasthttp)
  1569. // Get the status code which is set by fasthttp
  1570. fsStatus := c.fasthttp.Response.StatusCode()
  1571. // Set the status code set by the user if it is different from the fasthttp status code and 200
  1572. if status != fsStatus && status != StatusOK {
  1573. c.Status(status)
  1574. }
  1575. // Check for error
  1576. if status != StatusNotFound && fsStatus == StatusNotFound {
  1577. return NewError(StatusNotFound, fmt.Sprintf("sendfile: file %s not found", filename))
  1578. }
  1579. return nil
  1580. }
  1581. // SendStatus sets the HTTP status code and if the response body is empty,
  1582. // it sets the correct status message in the body.
  1583. func (c *Ctx) SendStatus(status int) error {
  1584. c.Status(status)
  1585. // Only set status body when there is no response body
  1586. if len(c.fasthttp.Response.Body()) == 0 {
  1587. return c.SendString(utils.StatusMessage(status))
  1588. }
  1589. return nil
  1590. }
  1591. // SendString sets the HTTP response body for string types.
  1592. // This means no type assertion, recommended for faster performance
  1593. func (c *Ctx) SendString(body string) error {
  1594. c.fasthttp.Response.SetBodyString(body)
  1595. return nil
  1596. }
  1597. // SendStream sets response body stream and optional body size.
  1598. func (c *Ctx) SendStream(stream io.Reader, size ...int) error {
  1599. if len(size) > 0 && size[0] >= 0 {
  1600. c.fasthttp.Response.SetBodyStream(stream, size[0])
  1601. } else {
  1602. c.fasthttp.Response.SetBodyStream(stream, -1)
  1603. }
  1604. return nil
  1605. }
  1606. // Set sets the response's HTTP header field to the specified key, value.
  1607. func (c *Ctx) Set(key, val string) {
  1608. c.fasthttp.Response.Header.Set(key, val)
  1609. }
  1610. func (c *Ctx) setCanonical(key, val string) {
  1611. c.fasthttp.Response.Header.SetCanonical(c.app.getBytes(key), c.app.getBytes(val))
  1612. }
  1613. // Subdomains returns a string slice of subdomains in the domain name of the request.
  1614. // The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.
  1615. func (c *Ctx) Subdomains(offset ...int) []string {
  1616. o := 2
  1617. if len(offset) > 0 {
  1618. o = offset[0]
  1619. }
  1620. subdomains := strings.Split(c.Hostname(), ".")
  1621. l := len(subdomains) - o
  1622. // Check index to avoid slice bounds out of range panic
  1623. if l < 0 {
  1624. l = len(subdomains)
  1625. }
  1626. subdomains = subdomains[:l]
  1627. return subdomains
  1628. }
  1629. // Stale is not implemented yet, pull requests are welcome!
  1630. func (c *Ctx) Stale() bool {
  1631. return !c.Fresh()
  1632. }
  1633. // Status sets the HTTP status for the response.
  1634. // This method is chainable.
  1635. func (c *Ctx) Status(status int) *Ctx {
  1636. c.fasthttp.Response.SetStatusCode(status)
  1637. return c
  1638. }
  1639. // String returns unique string representation of the ctx.
  1640. //
  1641. // The returned value may be useful for logging.
  1642. func (c *Ctx) String() string {
  1643. return fmt.Sprintf(
  1644. "#%016X - %s <-> %s - %s %s",
  1645. c.fasthttp.ID(),
  1646. c.fasthttp.LocalAddr(),
  1647. c.fasthttp.RemoteAddr(),
  1648. c.fasthttp.Request.Header.Method(),
  1649. c.fasthttp.URI().FullURI(),
  1650. )
  1651. }
  1652. // Type sets the Content-Type HTTP header to the MIME type specified by the file extension.
  1653. func (c *Ctx) Type(extension string, charset ...string) *Ctx {
  1654. if len(charset) > 0 {
  1655. c.fasthttp.Response.Header.SetContentType(utils.GetMIME(extension) + "; charset=" + charset[0])
  1656. } else {
  1657. c.fasthttp.Response.Header.SetContentType(utils.GetMIME(extension))
  1658. }
  1659. return c
  1660. }
  1661. // Vary adds the given header field to the Vary response header.
  1662. // This will append the header, if not already listed, otherwise leaves it listed in the current location.
  1663. func (c *Ctx) Vary(fields ...string) {
  1664. c.Append(HeaderVary, fields...)
  1665. }
  1666. // Write appends p into response body.
  1667. func (c *Ctx) Write(p []byte) (int, error) {
  1668. c.fasthttp.Response.AppendBody(p)
  1669. return len(p), nil
  1670. }
  1671. // Writef appends f & a into response body writer.
  1672. func (c *Ctx) Writef(f string, a ...interface{}) (int, error) {
  1673. //nolint:wrapcheck // This must not be wrapped
  1674. return fmt.Fprintf(c.fasthttp.Response.BodyWriter(), f, a...)
  1675. }
  1676. // WriteString appends s to response body.
  1677. func (c *Ctx) WriteString(s string) (int, error) {
  1678. c.fasthttp.Response.AppendBodyString(s)
  1679. return len(s), nil
  1680. }
  1681. // XHR returns a Boolean property, that is true, if the request's X-Requested-With header field is XMLHttpRequest,
  1682. // indicating that the request was issued by a client library (such as jQuery).
  1683. func (c *Ctx) XHR() bool {
  1684. return utils.EqualFoldBytes(c.app.getBytes(c.Get(HeaderXRequestedWith)), []byte("xmlhttprequest"))
  1685. }
  1686. // configDependentPaths set paths for route recognition and prepared paths for the user,
  1687. // here the features for caseSensitive, decoded paths, strict paths are evaluated
  1688. func (c *Ctx) configDependentPaths() {
  1689. c.pathBuffer = append(c.pathBuffer[0:0], c.pathOriginal...)
  1690. // If UnescapePath enabled, we decode the path and save it for the framework user
  1691. if c.app.config.UnescapePath {
  1692. c.pathBuffer = fasthttp.AppendUnquotedArg(c.pathBuffer[:0], c.pathBuffer)
  1693. }
  1694. c.path = c.app.getString(c.pathBuffer)
  1695. // another path is specified which is for routing recognition only
  1696. // use the path that was changed by the previous configuration flags
  1697. c.detectionPathBuffer = append(c.detectionPathBuffer[0:0], c.pathBuffer...)
  1698. // If CaseSensitive is disabled, we lowercase the original path
  1699. if !c.app.config.CaseSensitive {
  1700. c.detectionPathBuffer = utils.ToLowerBytes(c.detectionPathBuffer)
  1701. }
  1702. // If StrictRouting is disabled, we strip all trailing slashes
  1703. if !c.app.config.StrictRouting && len(c.detectionPathBuffer) > 1 && c.detectionPathBuffer[len(c.detectionPathBuffer)-1] == '/' {
  1704. c.detectionPathBuffer = utils.TrimRightBytes(c.detectionPathBuffer, '/')
  1705. }
  1706. c.detectionPath = c.app.getString(c.detectionPathBuffer)
  1707. // Define the path for dividing routes into areas for fast tree detection, so that fewer routes need to be traversed,
  1708. // since the first three characters area select a list of routes
  1709. c.treePath = c.treePath[0:0]
  1710. const maxDetectionPaths = 3
  1711. if len(c.detectionPath) >= maxDetectionPaths {
  1712. c.treePath = c.detectionPath[:maxDetectionPaths]
  1713. }
  1714. }
  1715. func (c *Ctx) IsProxyTrusted() bool {
  1716. if !c.app.config.EnableTrustedProxyCheck {
  1717. return true
  1718. }
  1719. ip := c.fasthttp.RemoteIP()
  1720. if _, trusted := c.app.config.trustedProxiesMap[ip.String()]; trusted {
  1721. return true
  1722. }
  1723. for _, ipNet := range c.app.config.trustedProxyRanges {
  1724. if ipNet.Contains(ip) {
  1725. return true
  1726. }
  1727. }
  1728. return false
  1729. }
  1730. var localHosts = [...]string{"127.0.0.1", "::1"}
  1731. // IsLocalHost will return true if address is a localhost address.
  1732. func (*Ctx) isLocalHost(address string) bool {
  1733. for _, h := range localHosts {
  1734. if address == h {
  1735. return true
  1736. }
  1737. }
  1738. return false
  1739. }
  1740. // IsFromLocal will return true if request came from local.
  1741. func (c *Ctx) IsFromLocal() bool {
  1742. return c.isLocalHost(c.fasthttp.RemoteIP().String())
  1743. }