ctx.go 55 KB

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