ctx.go 52 KB

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