ctx.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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. "encoding/json"
  9. "encoding/xml"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "log"
  14. "mime/multipart"
  15. "net/http"
  16. "path/filepath"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "text/template"
  21. "time"
  22. utils "github.com/gofiber/utils"
  23. schema "github.com/gorilla/schema"
  24. bytebufferpool "github.com/valyala/bytebufferpool"
  25. fasthttp "github.com/valyala/fasthttp"
  26. )
  27. // Ctx represents the Context which hold the HTTP request and response.
  28. // It has methods for the request query string, parameters, body, HTTP headers and so on.
  29. type Ctx struct {
  30. app *App // Reference to *App
  31. route *Route // Reference to *Route
  32. indexRoute int // Index of the current route
  33. indexHandler int // Index of the current handler
  34. method string // HTTP method
  35. methodINT int // HTTP method INT equivalent
  36. path string // Prettified HTTP path
  37. treePath string // Path for the search in the tree
  38. pathOriginal string // Original HTTP path
  39. values []string // Route parameter values
  40. err error // Contains error if passed to Next
  41. Fasthttp *fasthttp.RequestCtx // Reference to *fasthttp.RequestCtx
  42. matched bool // Non use route matched
  43. }
  44. // Range data for ctx.Range
  45. type Range struct {
  46. Type string
  47. Ranges []struct {
  48. Start int
  49. End int
  50. }
  51. }
  52. // Cookie data for ctx.Cookie
  53. type Cookie struct {
  54. Name string `json:"name"`
  55. Value string `json:"value"`
  56. Path string `json:"path"`
  57. Domain string `json:"domain"`
  58. Expires time.Time `json:"expires"`
  59. Secure bool `json:"secure"`
  60. HTTPOnly bool `json:"http_only"`
  61. SameSite string `json:"same_site"`
  62. }
  63. // Views is the interface that wraps the Render function.
  64. type Views interface {
  65. Load() error
  66. Render(io.Writer, string, interface{}, ...string) error
  67. }
  68. // AcquireCtx retrieves a new Ctx from the pool.
  69. func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) *Ctx {
  70. ctx := app.pool.Get().(*Ctx)
  71. // Set app reference
  72. ctx.app = app
  73. // Reset route and handler index
  74. ctx.indexRoute = -1
  75. ctx.indexHandler = 0
  76. // Reset matched flag
  77. ctx.matched = false
  78. // Set paths
  79. ctx.path = getString(fctx.URI().PathOriginal())
  80. ctx.pathOriginal = ctx.path
  81. // Set method
  82. ctx.method = getString(fctx.Request.Header.Method())
  83. ctx.methodINT = methodInt(ctx.method)
  84. // Attach *fasthttp.RequestCtx to ctx
  85. ctx.Fasthttp = fctx
  86. // Prettify path
  87. ctx.prettifyPath()
  88. return ctx
  89. }
  90. // ReleaseCtx releases the ctx back into the pool.
  91. func (app *App) ReleaseCtx(ctx *Ctx) {
  92. // Reset values
  93. ctx.route = nil
  94. ctx.values = nil
  95. ctx.Fasthttp = nil
  96. ctx.err = nil
  97. app.pool.Put(ctx)
  98. }
  99. // Accepts checks if the specified extensions or content types are acceptable.
  100. func (ctx *Ctx) Accepts(offers ...string) string {
  101. if len(offers) == 0 {
  102. return ""
  103. }
  104. header := ctx.Get(HeaderAccept)
  105. if header == "" {
  106. return offers[0]
  107. }
  108. spec, commaPos := "", 0
  109. for len(header) > 0 && commaPos != -1 {
  110. commaPos = strings.IndexByte(header, ',')
  111. if commaPos != -1 {
  112. spec = utils.Trim(header[:commaPos], ' ')
  113. } else {
  114. spec = header
  115. }
  116. if factorSign := strings.IndexByte(spec, ';'); factorSign != -1 {
  117. spec = spec[:factorSign]
  118. }
  119. for _, offer := range offers {
  120. mimetype := utils.GetMIME(offer)
  121. if len(spec) > 2 && spec[len(spec)-2:] == "/*" {
  122. if strings.HasPrefix(spec[:len(spec)-2], strings.Split(mimetype, "/")[0]) {
  123. return offer
  124. } else if spec == "*/*" {
  125. return offer
  126. }
  127. } else if strings.HasPrefix(spec, mimetype) {
  128. return offer
  129. }
  130. }
  131. if commaPos != -1 {
  132. header = header[commaPos+1:]
  133. }
  134. }
  135. return ""
  136. }
  137. // AcceptsCharsets checks if the specified charset is acceptable.
  138. func (ctx *Ctx) AcceptsCharsets(offers ...string) string {
  139. return getOffer(ctx.Get(HeaderAcceptCharset), offers...)
  140. }
  141. // AcceptsEncodings checks if the specified encoding is acceptable.
  142. func (ctx *Ctx) AcceptsEncodings(offers ...string) string {
  143. return getOffer(ctx.Get(HeaderAcceptEncoding), offers...)
  144. }
  145. // AcceptsLanguages checks if the specified language is acceptable.
  146. func (ctx *Ctx) AcceptsLanguages(offers ...string) string {
  147. return getOffer(ctx.Get(HeaderAcceptLanguage), offers...)
  148. }
  149. // App returns the *App reference to access Settings or ErrorHandler
  150. func (ctx *Ctx) App() *App {
  151. return ctx.app
  152. }
  153. // Append the specified value to the HTTP response header field.
  154. // If the header is not already set, it creates the header with the specified value.
  155. func (ctx *Ctx) Append(field string, values ...string) {
  156. if len(values) == 0 {
  157. return
  158. }
  159. h := getString(ctx.Fasthttp.Response.Header.Peek(field))
  160. originalH := h
  161. for _, value := range values {
  162. if len(h) == 0 {
  163. h = value
  164. } else if h != value && !strings.HasPrefix(h, value+",") && !strings.HasSuffix(h, " "+value) &&
  165. !strings.Contains(h, " "+value+",") {
  166. h += ", " + value
  167. }
  168. }
  169. if originalH != h {
  170. ctx.Set(field, h)
  171. }
  172. }
  173. // Attachment sets the HTTP response Content-Disposition header field to attachment.
  174. func (ctx *Ctx) Attachment(filename ...string) {
  175. if len(filename) > 0 {
  176. fname := filepath.Base(filename[0])
  177. ctx.Type(filepath.Ext(fname))
  178. ctx.Set(HeaderContentDisposition, `attachment; filename="`+quoteString(fname)+`"`)
  179. return
  180. }
  181. ctx.Set(HeaderContentDisposition, "attachment")
  182. }
  183. // BaseURL returns (protocol + host + base path).
  184. func (ctx *Ctx) BaseURL() string {
  185. // TODO: Could be improved: 53.8 ns/op 32 B/op 1 allocs/op
  186. // Should work like https://codeigniter.com/user_guide/helpers/url_helper.html
  187. return ctx.Protocol() + "://" + ctx.Hostname()
  188. }
  189. // Body contains the raw body submitted in a POST request.
  190. // Returned value is only valid within the handler. Do not store any references.
  191. // Make copies or use the Immutable setting instead.
  192. func (ctx *Ctx) Body() string {
  193. return getString(ctx.Fasthttp.Request.Body())
  194. }
  195. // decoderPool helps to improve BodyParser's and QueryParser's performance
  196. var decoderPool = &sync.Pool{New: func() interface{} {
  197. var decoder = schema.NewDecoder()
  198. decoder.IgnoreUnknownKeys(true)
  199. return decoder
  200. }}
  201. // BodyParser binds the request body to a struct.
  202. // It supports decoding the following content types based on the Content-Type header:
  203. // application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data
  204. func (ctx *Ctx) BodyParser(out interface{}) error {
  205. // Get decoder from pool
  206. schemaDecoder := decoderPool.Get().(*schema.Decoder)
  207. defer decoderPool.Put(schemaDecoder)
  208. // Get content-type
  209. ctype := getString(ctx.Fasthttp.Request.Header.ContentType())
  210. // Parse body accordingly
  211. if strings.HasPrefix(ctype, MIMEApplicationJSON) {
  212. schemaDecoder.SetAliasTag("json")
  213. return json.Unmarshal(ctx.Fasthttp.Request.Body(), out)
  214. } else if strings.HasPrefix(ctype, MIMEApplicationForm) {
  215. schemaDecoder.SetAliasTag("form")
  216. data := make(map[string][]string)
  217. ctx.Fasthttp.PostArgs().VisitAll(func(key []byte, val []byte) {
  218. data[getString(key)] = append(data[getString(key)], getString(val))
  219. })
  220. return schemaDecoder.Decode(out, data)
  221. } else if strings.HasPrefix(ctype, MIMEMultipartForm) {
  222. schemaDecoder.SetAliasTag("form")
  223. data, err := ctx.Fasthttp.MultipartForm()
  224. if err != nil {
  225. return err
  226. }
  227. return schemaDecoder.Decode(out, data.Value)
  228. } else if strings.HasPrefix(ctype, MIMETextXML) || strings.HasPrefix(ctype, MIMEApplicationXML) {
  229. schemaDecoder.SetAliasTag("xml")
  230. return xml.Unmarshal(ctx.Fasthttp.Request.Body(), out)
  231. }
  232. // Query params in BodyParser is deprecated
  233. if ctx.Fasthttp.QueryArgs().Len() > 0 {
  234. fmt.Println("bodyparser: parsing query strings is deprecated since v1.12.7, please use `ctx.QueryParser` instead")
  235. return ctx.QueryParser(out)
  236. }
  237. // No suitable content type found
  238. return fmt.Errorf("bodyparser: cannot parse content-type: %v", ctype)
  239. }
  240. // QueryParser binds the query string to a struct.
  241. func (ctx *Ctx) QueryParser(out interface{}) error {
  242. if ctx.Fasthttp.QueryArgs().Len() < 1 {
  243. return nil
  244. }
  245. // Get decoder from pool
  246. var decoder = decoderPool.Get().(*schema.Decoder)
  247. defer decoderPool.Put(decoder)
  248. // Set correct alias tag
  249. decoder.SetAliasTag("query")
  250. data := make(map[string][]string)
  251. ctx.Fasthttp.QueryArgs().VisitAll(func(key []byte, val []byte) {
  252. data[getString(key)] = append(data[getString(key)], getString(val))
  253. })
  254. return decoder.Decode(out, data)
  255. }
  256. // ClearCookie expires a specific cookie by key on the client side.
  257. // If no key is provided it expires all cookies that came with the request.
  258. func (ctx *Ctx) ClearCookie(key ...string) {
  259. if len(key) > 0 {
  260. for i := range key {
  261. ctx.Fasthttp.Response.Header.DelClientCookie(key[i])
  262. }
  263. return
  264. }
  265. ctx.Fasthttp.Request.Header.VisitAllCookie(func(k, v []byte) {
  266. ctx.Fasthttp.Response.Header.DelClientCookieBytes(k)
  267. })
  268. }
  269. // Context returns context.Context that carries a deadline, a cancellation signal,
  270. // and other values across API boundaries.
  271. func (ctx *Ctx) Context() context.Context {
  272. return ctx.Fasthttp
  273. }
  274. // Cookie sets a cookie by passing a cookie struct.
  275. func (ctx *Ctx) Cookie(cookie *Cookie) {
  276. fcookie := fasthttp.AcquireCookie()
  277. fcookie.SetKey(cookie.Name)
  278. fcookie.SetValue(cookie.Value)
  279. fcookie.SetPath(cookie.Path)
  280. fcookie.SetDomain(cookie.Domain)
  281. fcookie.SetExpire(cookie.Expires)
  282. fcookie.SetSecure(cookie.Secure)
  283. fcookie.SetHTTPOnly(cookie.HTTPOnly)
  284. switch utils.ToLower(cookie.SameSite) {
  285. case "strict":
  286. fcookie.SetSameSite(fasthttp.CookieSameSiteStrictMode)
  287. case "none":
  288. fcookie.SetSameSite(fasthttp.CookieSameSiteNoneMode)
  289. default:
  290. fcookie.SetSameSite(fasthttp.CookieSameSiteLaxMode)
  291. }
  292. ctx.Fasthttp.Response.Header.SetCookie(fcookie)
  293. fasthttp.ReleaseCookie(fcookie)
  294. }
  295. // Cookies is used for getting a cookie value by key.
  296. // Defaults to the empty string "" if the cookie doesn't exist.
  297. // If a default value is given, it will return that value if the cookie doesn't exist.
  298. // The returned value is only valid within the handler. Do not store any references.
  299. // Make copies or use the Immutable setting to use the value outside the Handler.
  300. func (ctx *Ctx) Cookies(key string, defaultValue ...string) string {
  301. return defaultString(getString(ctx.Fasthttp.Request.Header.Cookie(key)), defaultValue)
  302. }
  303. // Download transfers the file from path as an attachment.
  304. // Typically, browsers will prompt the user for download.
  305. // By default, the Content-Disposition header filename= parameter is the filepath (this typically appears in the browser dialog).
  306. // Override this default with the filename parameter.
  307. func (ctx *Ctx) Download(file string, filename ...string) error {
  308. fname := filepath.Base(file)
  309. if len(filename) > 0 {
  310. fname = filename[0]
  311. }
  312. ctx.Set(HeaderContentDisposition, `attachment; filename="`+quoteString(fname)+`"`)
  313. return ctx.SendFile(file)
  314. }
  315. // Error contains the error information passed via the Next(err) method.
  316. func (ctx *Ctx) Error() error {
  317. return ctx.err
  318. }
  319. // Format performs content-negotiation on the Accept HTTP header.
  320. // It uses Accepts to select a proper format.
  321. // If the header is not specified or there is no proper format, text/plain is used.
  322. func (ctx *Ctx) Format(body interface{}) {
  323. // Get accepted content type
  324. accept := ctx.Accepts("html", "json", "txt", "xml")
  325. // Set accepted content type
  326. ctx.Type(accept)
  327. // Type convert provided body
  328. var b string
  329. switch val := body.(type) {
  330. case string:
  331. b = val
  332. case []byte:
  333. b = getString(val)
  334. default:
  335. b = fmt.Sprintf("%v", val)
  336. }
  337. // Format based on the accept content type
  338. switch accept {
  339. case "html":
  340. ctx.SendString("<p>" + b + "</p>")
  341. case "json":
  342. if err := ctx.JSON(body); err != nil {
  343. ctx.Send(body) // Fallback
  344. log.Println("Format: error serializing json ", err)
  345. }
  346. case "txt":
  347. ctx.SendString(b)
  348. case "xml":
  349. raw, err := xml.Marshal(body)
  350. if err != nil {
  351. ctx.Send(body) // Fallback
  352. log.Println("Format: error serializing xml ", err)
  353. } else {
  354. ctx.Fasthttp.Response.SetBodyRaw(raw)
  355. }
  356. default:
  357. ctx.SendString(b)
  358. }
  359. }
  360. // FormFile returns the first file by key from a MultipartForm.
  361. func (ctx *Ctx) FormFile(key string) (*multipart.FileHeader, error) {
  362. return ctx.Fasthttp.FormFile(key)
  363. }
  364. // FormValue returns the first value by key from a MultipartForm.
  365. // Returned value is only valid within the handler. Do not store any references.
  366. // Make copies or use the Immutable setting instead.
  367. func (ctx *Ctx) FormValue(key string) (value string) {
  368. return getString(ctx.Fasthttp.FormValue(key))
  369. }
  370. // Fresh returns true when the response is still “fresh” in the client's cache,
  371. // otherwise false is returned to indicate that the client cache is now stale
  372. // and the full response should be sent.
  373. // When a client sends the Cache-Control: no-cache request header to indicate an end-to-end
  374. // reload request, this module will return false to make handling these requests transparent.
  375. // https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33
  376. func (ctx *Ctx) Fresh() bool {
  377. // fields
  378. var modifiedSince = ctx.Get(HeaderIfModifiedSince)
  379. var noneMatch = ctx.Get(HeaderIfNoneMatch)
  380. // unconditional request
  381. if modifiedSince == "" && noneMatch == "" {
  382. return false
  383. }
  384. // Always return stale when Cache-Control: no-cache
  385. // to support end-to-end reload requests
  386. // https://tools.ietf.org/html/rfc2616#section-14.9.4
  387. cacheControl := ctx.Get(HeaderCacheControl)
  388. if cacheControl != "" && isNoCache(cacheControl) {
  389. return false
  390. }
  391. // if-none-match
  392. if noneMatch != "" && noneMatch != "*" {
  393. var etag = getString(ctx.Fasthttp.Response.Header.Peek(HeaderETag))
  394. if etag == "" {
  395. return false
  396. }
  397. if isEtagStale(etag, getBytes(noneMatch)) {
  398. return false
  399. }
  400. if modifiedSince != "" {
  401. var lastModified = getString(ctx.Fasthttp.Response.Header.Peek(HeaderLastModified))
  402. if lastModified != "" {
  403. lastModifiedTime, err := http.ParseTime(lastModified)
  404. if err != nil {
  405. return false
  406. }
  407. modifiedSinceTime, err := http.ParseTime(modifiedSince)
  408. if err != nil {
  409. return false
  410. }
  411. return lastModifiedTime.Before(modifiedSinceTime)
  412. }
  413. }
  414. }
  415. return true
  416. }
  417. // Get returns the HTTP request header specified by field.
  418. // Field names are case-insensitive
  419. // Returned value is only valid within the handler. Do not store any references.
  420. // Make copies or use the Immutable setting instead.
  421. func (ctx *Ctx) Get(key string, defaultValue ...string) string {
  422. return defaultString(getString(ctx.Fasthttp.Request.Header.Peek(key)), defaultValue)
  423. }
  424. // Hostname contains the hostname derived from the Host HTTP header.
  425. // Returned value is only valid within the handler. Do not store any references.
  426. // Make copies or use the Immutable setting instead.
  427. func (ctx *Ctx) Hostname() string {
  428. return getString(ctx.Fasthttp.URI().Host())
  429. }
  430. // IP returns the remote IP address of the request.
  431. func (ctx *Ctx) IP() string {
  432. return ctx.Fasthttp.RemoteIP().String()
  433. }
  434. // IPs returns an string slice of IP addresses specified in the X-Forwarded-For request header.
  435. func (ctx *Ctx) IPs() (ips []string) {
  436. header := ctx.Fasthttp.Request.Header.Peek(HeaderXForwardedFor)
  437. if len(header) == 0 {
  438. return
  439. }
  440. ips = make([]string, bytes.Count(header, []byte(","))+1)
  441. var commaPos, i int
  442. for {
  443. commaPos = bytes.IndexByte(header, ',')
  444. if commaPos != -1 {
  445. ips[i] = getString(header[:commaPos])
  446. header, i = header[commaPos+2:], i+1
  447. } else {
  448. ips[i] = getString(header)
  449. return
  450. }
  451. }
  452. }
  453. // Is returns the matching content type,
  454. // if the incoming request's Content-Type HTTP header field matches the MIME type specified by the type parameter
  455. func (ctx *Ctx) Is(extension string) bool {
  456. extensionHeader := utils.GetMIME(extension)
  457. if extensionHeader == "" {
  458. return false
  459. }
  460. return strings.HasPrefix(
  461. utils.TrimLeft(utils.GetString(ctx.Fasthttp.Request.Header.ContentType()), ' '),
  462. extensionHeader,
  463. )
  464. }
  465. // JSON converts any interface or string to JSON.
  466. // This method also sets the content header to application/json.
  467. func (ctx *Ctx) JSON(data interface{}) error {
  468. raw, err := json.Marshal(data)
  469. // Check for errors
  470. if err != nil {
  471. return err
  472. }
  473. // Set http headers
  474. ctx.Fasthttp.Response.Header.SetContentType(MIMEApplicationJSON)
  475. ctx.Fasthttp.Response.SetBodyRaw(raw)
  476. return nil
  477. }
  478. // JSONP sends a JSON response with JSONP support.
  479. // This method is identical to JSON, except that it opts-in to JSONP callback support.
  480. // By default, the callback name is simply callback.
  481. func (ctx *Ctx) JSONP(data interface{}, callback ...string) error {
  482. raw, err := json.Marshal(data)
  483. if err != nil {
  484. return err
  485. }
  486. var result, cb string
  487. if len(callback) > 0 {
  488. cb = callback[0]
  489. } else {
  490. cb = "callback"
  491. }
  492. result = cb + "(" + getString(raw) + ");"
  493. ctx.Set(HeaderXContentTypeOptions, "nosniff")
  494. ctx.Fasthttp.Response.Header.SetContentType(MIMEApplicationJavaScriptCharsetUTF8)
  495. ctx.SendString(result)
  496. return nil
  497. }
  498. // Links joins the links followed by the property to populate the response's Link HTTP header field.
  499. func (ctx *Ctx) Links(link ...string) {
  500. if len(link) == 0 {
  501. return
  502. }
  503. bb := bytebufferpool.Get()
  504. for i := range link {
  505. if i%2 == 0 {
  506. _ = bb.WriteByte('<')
  507. _, _ = bb.WriteString(link[i])
  508. _ = bb.WriteByte('>')
  509. } else {
  510. _, _ = bb.WriteString(`; rel="` + link[i] + `",`)
  511. }
  512. }
  513. ctx.Set(HeaderLink, utils.TrimRight(getString(bb.Bytes()), ','))
  514. bytebufferpool.Put(bb)
  515. }
  516. // Locals makes it possible to pass interface{} values under string keys scoped to the request
  517. // and therefore available to all following routes that match the request.
  518. func (ctx *Ctx) Locals(key string, value ...interface{}) (val interface{}) {
  519. if len(value) == 0 {
  520. return ctx.Fasthttp.UserValue(key)
  521. }
  522. ctx.Fasthttp.SetUserValue(key, value[0])
  523. return value[0]
  524. }
  525. // Location sets the response Location HTTP header to the specified path parameter.
  526. func (ctx *Ctx) Location(path string) {
  527. ctx.Set(HeaderLocation, path)
  528. }
  529. // Method contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.
  530. func (ctx *Ctx) Method(override ...string) string {
  531. if len(override) > 0 {
  532. method := utils.ToUpper(override[0])
  533. mINT := methodInt(method)
  534. if mINT == -1 {
  535. return ctx.method
  536. }
  537. ctx.method = method
  538. ctx.methodINT = mINT
  539. }
  540. return ctx.method
  541. }
  542. // MultipartForm parse form entries from binary.
  543. // This returns a map[string][]string, so given a key the value will be a string slice.
  544. func (ctx *Ctx) MultipartForm() (*multipart.Form, error) {
  545. return ctx.Fasthttp.MultipartForm()
  546. }
  547. // Next executes the next method in the stack that matches the current route.
  548. // You can pass an optional error for custom error handling.
  549. func (ctx *Ctx) Next(err ...error) {
  550. if len(err) > 0 {
  551. ctx.err = err[0]
  552. ctx.app.Settings.ErrorHandler(ctx, ctx.err)
  553. return
  554. }
  555. // Increment handler index
  556. ctx.indexHandler++
  557. // Did we executed all route handlers?
  558. if ctx.indexHandler < len(ctx.route.Handlers) {
  559. // Continue route stack
  560. ctx.route.Handlers[ctx.indexHandler](ctx)
  561. } else {
  562. // Continue handler stack
  563. ctx.app.next(ctx)
  564. }
  565. }
  566. // OriginalURL contains the original request URL.
  567. // Returned value is only valid within the handler. Do not store any references.
  568. // Make copies or use the Immutable setting to use the value outside the Handler.
  569. func (ctx *Ctx) OriginalURL() string {
  570. return getString(ctx.Fasthttp.Request.Header.RequestURI())
  571. }
  572. // Params is used to get the route parameters.
  573. // Defaults to empty string "" if the param doesn't exist.
  574. // If a default value is given, it will return that value if the param doesn't exist.
  575. // Returned value is only valid within the handler. Do not store any references.
  576. // Make copies or use the Immutable setting to use the value outside the Handler.
  577. func (ctx *Ctx) Params(key string, defaultValue ...string) string {
  578. if key == "*" || key == "+" {
  579. key += "1"
  580. }
  581. for i := range ctx.route.Params {
  582. if len(key) != len(ctx.route.Params[i]) {
  583. continue
  584. }
  585. if ctx.route.Params[i] == key {
  586. // in case values are not here
  587. if len(ctx.values) <= i || len(ctx.values[i]) == 0 {
  588. break
  589. }
  590. return ctx.values[i]
  591. }
  592. }
  593. return defaultString("", defaultValue)
  594. }
  595. // Path returns the path part of the request URL.
  596. // Optionally, you could override the path.
  597. func (ctx *Ctx) Path(override ...string) string {
  598. if len(override) != 0 && ctx.path != override[0] {
  599. // Set new path to context
  600. ctx.path = override[0]
  601. ctx.pathOriginal = ctx.path
  602. // Set new path to request context
  603. ctx.Fasthttp.Request.URI().SetPath(ctx.pathOriginal)
  604. // Prettify path
  605. ctx.prettifyPath()
  606. }
  607. return ctx.pathOriginal
  608. }
  609. // Protocol contains the request protocol string: http or https for TLS requests.
  610. func (ctx *Ctx) Protocol() string {
  611. if ctx.Fasthttp.IsTLS() {
  612. return "https"
  613. }
  614. scheme := "http"
  615. ctx.Fasthttp.Request.Header.VisitAll(func(key, val []byte) {
  616. if len(key) < 12 {
  617. return // X-Forwarded-
  618. } else if bytes.HasPrefix(key, []byte("X-Forwarded-")) {
  619. if bytes.Equal(key, []byte(HeaderXForwardedProto)) {
  620. scheme = getString(val)
  621. } else if bytes.Equal(key, []byte(HeaderXForwardedProtocol)) {
  622. scheme = getString(val)
  623. } else if bytes.Equal(key, []byte(HeaderXForwardedSsl)) && bytes.Equal(val, []byte("on")) {
  624. scheme = "https"
  625. }
  626. } else if bytes.Equal(key, []byte(HeaderXUrlScheme)) {
  627. scheme = getString(val)
  628. }
  629. })
  630. return scheme
  631. }
  632. // Query returns the query string parameter in the url.
  633. // Defaults to empty string "" if the query doesn't exist.
  634. // If a default value is given, it will return that value if the query doesn't exist.
  635. // Returned value is only valid within the handler. Do not store any references.
  636. // Make copies or use the Immutable setting to use the value outside the Handler.
  637. func (ctx *Ctx) Query(key string, defaultValue ...string) string {
  638. return defaultString(getString(ctx.Fasthttp.QueryArgs().Peek(key)), defaultValue)
  639. }
  640. var (
  641. ErrRangeMalformed = errors.New("range: malformed range header string")
  642. ErrRangeUnsatisfiable = errors.New("range: unsatisfiable range")
  643. )
  644. // Range returns a struct containing the type and a slice of ranges.
  645. func (ctx *Ctx) Range(size int) (rangeData Range, err error) {
  646. rangeStr := ctx.Get(HeaderRange)
  647. if rangeStr == "" || !strings.Contains(rangeStr, "=") {
  648. err = ErrRangeMalformed
  649. return
  650. }
  651. data := strings.Split(rangeStr, "=")
  652. if len(data) != 2 {
  653. err = ErrRangeMalformed
  654. return
  655. }
  656. rangeData.Type = data[0]
  657. arr := strings.Split(data[1], ",")
  658. for i := 0; i < len(arr); i++ {
  659. item := strings.Split(arr[i], "-")
  660. if len(item) == 1 {
  661. err = ErrRangeMalformed
  662. return
  663. }
  664. start, startErr := strconv.Atoi(item[0])
  665. end, endErr := strconv.Atoi(item[1])
  666. if startErr != nil { // -nnn
  667. start = size - end
  668. end = size - 1
  669. } else if endErr != nil { // nnn-
  670. end = size - 1
  671. }
  672. if end > size-1 { // limit last-byte-pos to current length
  673. end = size - 1
  674. }
  675. if start > end || start < 0 {
  676. continue
  677. }
  678. rangeData.Ranges = append(rangeData.Ranges, struct {
  679. Start int
  680. End int
  681. }{
  682. start,
  683. end,
  684. })
  685. }
  686. if len(rangeData.Ranges) < 1 {
  687. err = ErrRangeUnsatisfiable
  688. return
  689. }
  690. return
  691. }
  692. // Redirect to the URL derived from the specified path, with specified status.
  693. // If status is not specified, status defaults to 302 Found.
  694. func (ctx *Ctx) Redirect(location string, status ...int) {
  695. ctx.Set(HeaderLocation, location)
  696. if len(status) > 0 {
  697. ctx.Status(status[0])
  698. } else {
  699. ctx.Status(StatusFound)
  700. }
  701. }
  702. // Render a template with data and sends a text/html response.
  703. // We support the following engines: html, amber, handlebars, mustache, pug
  704. func (ctx *Ctx) Render(name string, bind interface{}, layouts ...string) (err error) {
  705. // Get new buffer from pool
  706. buf := bytebufferpool.Get()
  707. defer bytebufferpool.Put(buf)
  708. if ctx.app.Settings.Views != nil {
  709. // Render template from Views
  710. if err := ctx.app.Settings.Views.Render(buf, name, bind, layouts...); err != nil {
  711. return err
  712. }
  713. } else {
  714. // Render raw template using 'name' as filepath if no engine is set
  715. var tmpl *template.Template
  716. if _, err = readContent(buf, name); err != nil {
  717. return err
  718. }
  719. // Parse template
  720. if tmpl, err = template.New("").Parse(getString(buf.Bytes())); err != nil {
  721. return err
  722. }
  723. buf.Reset()
  724. // Render template
  725. if err = tmpl.Execute(buf, bind); err != nil {
  726. return err
  727. }
  728. }
  729. // Set Content-Type to text/html
  730. ctx.Fasthttp.Response.Header.SetContentType(MIMETextHTMLCharsetUTF8)
  731. // Set rendered template to body
  732. ctx.Fasthttp.Response.SetBody(buf.Bytes())
  733. // Return err if exist
  734. return
  735. }
  736. // Route returns the matched Route struct.
  737. func (ctx *Ctx) Route() *Route {
  738. if ctx.route == nil {
  739. // Fallback for fasthttp error handler
  740. return &Route{
  741. path: ctx.pathOriginal,
  742. Path: ctx.pathOriginal,
  743. Method: ctx.method,
  744. Handlers: make([]Handler, 0),
  745. }
  746. }
  747. return ctx.route
  748. }
  749. // SaveFile saves any multipart file to disk.
  750. func (ctx *Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error {
  751. return fasthttp.SaveMultipartFile(fileheader, path)
  752. }
  753. // Secure returns a boolean property, that is true, if a TLS connection is established.
  754. func (ctx *Ctx) Secure() bool {
  755. return ctx.Fasthttp.IsTLS()
  756. }
  757. // Send sets the HTTP response body. The input can be of any type, io.Reader is also supported.
  758. func (ctx *Ctx) Send(bodies ...interface{}) {
  759. // Reset response body
  760. ctx.SendString("")
  761. // Write response body
  762. ctx.Write(bodies...)
  763. }
  764. // SendBytes sets the HTTP response body for []byte types without copying it.
  765. // From this point onward the body argument must not be changed.
  766. func (ctx *Ctx) SendBytes(body []byte) {
  767. ctx.Fasthttp.Response.SetBodyRaw(body)
  768. }
  769. var fsOnce sync.Once
  770. var sendFileFS *fasthttp.FS
  771. var sendFileHandler fasthttp.RequestHandler
  772. // SendFile transfers the file from the given path.
  773. // The file is not compressed by default, enable this by passing a 'true' argument
  774. // Sets the Content-Type response HTTP header field based on the filenames extension.
  775. func (ctx *Ctx) SendFile(file string, compress ...bool) error {
  776. // https://github.com/valyala/fasthttp/blob/master/fs.go#L81
  777. fsOnce.Do(func() {
  778. sendFileFS = &fasthttp.FS{
  779. Root: "/",
  780. GenerateIndexPages: false,
  781. AcceptByteRange: true,
  782. Compress: true,
  783. CompressedFileSuffix: ctx.app.Settings.CompressedFileSuffix,
  784. CacheDuration: 10 * time.Second,
  785. IndexNames: []string{"index.html"},
  786. PathNotFound: func(ctx *fasthttp.RequestCtx) {
  787. ctx.Response.SetStatusCode(StatusNotFound)
  788. },
  789. }
  790. sendFileHandler = sendFileFS.NewRequestHandler()
  791. })
  792. // Keep original path for mutable params
  793. ctx.pathOriginal = utils.ImmutableString(ctx.pathOriginal)
  794. // Disable compression
  795. if len(compress) <= 0 || !compress[0] {
  796. // https://github.com/valyala/fasthttp/blob/master/fs.go#L46
  797. ctx.Fasthttp.Request.Header.Del(HeaderAcceptEncoding)
  798. }
  799. // https://github.com/valyala/fasthttp/blob/master/fs.go#L85
  800. if len(file) == 0 || file[0] != '/' {
  801. hasTrailingSlash := len(file) > 0 && file[len(file)-1] == '/'
  802. var err error
  803. if file, err = filepath.Abs(file); err != nil {
  804. return err
  805. }
  806. if hasTrailingSlash {
  807. file += "/"
  808. }
  809. }
  810. // Set new URI for fileHandler
  811. ctx.Fasthttp.Request.SetRequestURI(file)
  812. // Save status code
  813. status := ctx.Fasthttp.Response.StatusCode()
  814. // Serve file
  815. sendFileHandler(ctx.Fasthttp)
  816. // Get the status code which is set by fasthttp
  817. fsStatus := ctx.Fasthttp.Response.StatusCode()
  818. // Set the status code set by the user if it is different from the fasthttp status code and 200
  819. if status != fsStatus && status != StatusOK {
  820. ctx.Status(status)
  821. }
  822. // Check for error
  823. if status != StatusNotFound && fsStatus == StatusNotFound {
  824. return fmt.Errorf("sendfile: file %s not found", file)
  825. }
  826. return nil
  827. }
  828. // SendStatus sets the HTTP status code and if the response body is empty,
  829. // it sets the correct status message in the body.
  830. func (ctx *Ctx) SendStatus(status int) {
  831. ctx.Status(status)
  832. // Only set status body when there is no response body
  833. if len(ctx.Fasthttp.Response.Body()) == 0 {
  834. ctx.SendString(utils.StatusMessage(status))
  835. }
  836. }
  837. // SendString sets the HTTP response body for string types.
  838. // This means no type assertion, recommended for faster performance
  839. func (ctx *Ctx) SendString(body string) {
  840. ctx.Fasthttp.Response.SetBodyString(body)
  841. }
  842. // SendStream sets response body stream and optional body size.
  843. func (ctx *Ctx) SendStream(stream io.Reader, size ...int) {
  844. if len(size) > 0 && size[0] >= 0 {
  845. ctx.Fasthttp.Response.SetBodyStream(stream, size[0])
  846. } else {
  847. ctx.Fasthttp.Response.SetBodyStream(stream, -1)
  848. ctx.Set(HeaderContentLength, strconv.Itoa(len(ctx.Fasthttp.Response.Body())))
  849. }
  850. }
  851. // Set sets the response's HTTP header field to the specified key, value.
  852. func (ctx *Ctx) Set(key string, val string) {
  853. ctx.Fasthttp.Response.Header.Set(key, val)
  854. }
  855. // Subdomains returns a string slice of subdomains in the domain name of the request.
  856. // The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.
  857. func (ctx *Ctx) Subdomains(offset ...int) []string {
  858. o := 2
  859. if len(offset) > 0 {
  860. o = offset[0]
  861. }
  862. subdomains := strings.Split(ctx.Hostname(), ".")
  863. l := len(subdomains) - o
  864. // Check index to avoid slice bounds out of range panic
  865. if l < 0 {
  866. l = len(subdomains)
  867. }
  868. subdomains = subdomains[:l]
  869. return subdomains
  870. }
  871. // Stale is not implemented yet, pull requests are welcome!
  872. func (ctx *Ctx) Stale() bool {
  873. return !ctx.Fresh()
  874. }
  875. // Status sets the HTTP status for the response.
  876. // This method is chainable.
  877. func (ctx *Ctx) Status(status int) *Ctx {
  878. ctx.Fasthttp.Response.SetStatusCode(status)
  879. return ctx
  880. }
  881. // Type sets the Content-Type HTTP header to the MIME type specified by the file extension.
  882. func (ctx *Ctx) Type(extension string, charset ...string) *Ctx {
  883. if len(charset) > 0 {
  884. ctx.Fasthttp.Response.Header.SetContentType(utils.GetMIME(extension) + "; charset=" + charset[0])
  885. } else {
  886. ctx.Fasthttp.Response.Header.SetContentType(utils.GetMIME(extension))
  887. }
  888. return ctx
  889. }
  890. // Vary adds the given header field to the Vary response header.
  891. // This will append the header, if not already listed, otherwise leaves it listed in the current location.
  892. func (ctx *Ctx) Vary(fields ...string) {
  893. ctx.Append(HeaderVary, fields...)
  894. }
  895. // Write appends any input to the HTTP body response, io.Reader is also supported as input.
  896. func (ctx *Ctx) Write(bodies ...interface{}) {
  897. for i := range bodies {
  898. switch body := bodies[i].(type) {
  899. case string:
  900. ctx.Fasthttp.Response.AppendBodyString(body)
  901. case []byte:
  902. ctx.Fasthttp.Response.AppendBodyString(getString(body))
  903. case int:
  904. ctx.Fasthttp.Response.AppendBodyString(strconv.Itoa(body))
  905. case bool:
  906. ctx.Fasthttp.Response.AppendBodyString(strconv.FormatBool(body))
  907. case io.Reader:
  908. ctx.Fasthttp.Response.SetBodyStream(body, -1)
  909. ctx.Set(HeaderContentLength, strconv.Itoa(len(ctx.Fasthttp.Response.Body())))
  910. default:
  911. ctx.Fasthttp.Response.AppendBodyString(fmt.Sprintf("%v", body))
  912. }
  913. }
  914. }
  915. // XHR returns a Boolean property, that is true, if the request's X-Requested-With header field is XMLHttpRequest,
  916. // indicating that the request was issued by a client library (such as jQuery).
  917. func (ctx *Ctx) XHR() bool {
  918. return strings.EqualFold(ctx.Get(HeaderXRequestedWith), "xmlhttprequest")
  919. }
  920. // prettifyPath ...
  921. func (ctx *Ctx) prettifyPath() {
  922. // If UnescapePath enabled, we decode the path
  923. if ctx.app.Settings.UnescapePath {
  924. pathBytes := getBytes(ctx.path)
  925. pathBytes = fasthttp.AppendUnquotedArg(pathBytes[:0], pathBytes)
  926. ctx.path = getString(pathBytes)
  927. }
  928. // If CaseSensitive is disabled, we lowercase the original path
  929. if !ctx.app.Settings.CaseSensitive {
  930. // We are making a copy here to keep access to the original path
  931. ctx.path = utils.ToLower(ctx.path)
  932. }
  933. // If StrictRouting is disabled, we strip all trailing slashes
  934. if !ctx.app.Settings.StrictRouting && len(ctx.path) > 1 && ctx.path[len(ctx.path)-1] == '/' {
  935. ctx.path = utils.TrimRight(ctx.path, '/')
  936. }
  937. ctx.treePath = ctx.treePath[0:0]
  938. if len(ctx.path) >= 3 {
  939. ctx.treePath = ctx.path[:3]
  940. }
  941. }