1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-21 07:52:53 +00:00
fiber/ctx.go

1104 lines
33 KiB
Go
Raw Normal View History

// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
// 🤖 Github Repository: https://github.com/gofiber/fiber
// 📌 API Documentation: https://docs.gofiber.io
2020-02-21 18:07:43 +01:00
package fiber
import (
2020-03-22 20:31:58 +01:00
"bytes"
2020-02-21 18:07:43 +01:00
"encoding/xml"
2020-06-06 20:45:05 +02:00
"errors"
2020-02-21 18:07:43 +01:00
"fmt"
"io"
2020-02-21 18:07:43 +01:00
"mime/multipart"
"net/http"
2020-02-21 18:07:43 +01:00
"path/filepath"
"reflect"
2020-02-29 21:00:54 +08:00
"strconv"
2020-02-21 18:07:43 +01:00
"strings"
"sync"
"text/template"
2020-02-21 18:07:43 +01:00
"time"
2020-09-14 09:24:48 +02:00
"github.com/gofiber/fiber/v2/internal/bytebufferpool"
"github.com/gofiber/fiber/v2/internal/encoding/json"
"github.com/gofiber/fiber/v2/internal/schema"
"github.com/gofiber/fiber/v2/utils"
2020-09-13 11:20:11 +02:00
"github.com/valyala/fasthttp"
2020-02-21 18:07:43 +01:00
)
2020-09-13 11:20:11 +02:00
// maxParams defines the maximum number of parameters per route.
const maxParams = 30
2020-02-21 18:07:43 +01:00
// Ctx represents the Context which hold the HTTP request and response.
// It has methods for the request query string, parameters, body, HTTP headers and so on.
type Ctx struct {
app *App // Reference to *App
route *Route // Reference to *Route
indexRoute int // Index of the current route
indexHandler int // Index of the current handler
method string // HTTP method
2020-06-30 00:27:28 +02:00
methodINT int // HTTP method INT equivalent
2020-09-13 11:20:11 +02:00
path string // Prettified HTTP path -> string copy from pathBuffer
pathBuffer []byte // Prettified HTTP path buffer
treePath string // Path for the search in the tree
pathOriginal string // Original HTTP path
2020-09-13 11:20:11 +02:00
values [maxParams]string // Route parameter values
fasthttp *fasthttp.RequestCtx // Reference to *fasthttp.RequestCtx
matched bool // Non use route matched
}
2020-09-13 11:20:11 +02:00
// Range data for c.Range
type Range struct {
2020-02-29 21:00:54 +08:00
Type string
Ranges []struct {
Start int
End int
2020-02-29 21:00:54 +08:00
}
}
2020-09-13 11:20:11 +02:00
// Cookie data for c.Cookie
2020-03-04 12:30:29 +01:00
type Cookie struct {
2020-07-02 20:26:38 +02:00
Name string `json:"name"`
Value string `json:"value"`
Path string `json:"path"`
Domain string `json:"domain"`
2020-09-30 15:31:46 +02:00
MaxAge int `json:"max_age"`
2020-07-02 20:26:38 +02:00
Expires time.Time `json:"expires"`
Secure bool `json:"secure"`
HTTPOnly bool `json:"http_only"`
SameSite string `json:"same_site"`
2020-03-04 12:30:29 +01:00
}
2020-06-12 12:29:57 +02:00
// Views is the interface that wraps the Render function.
type Views interface {
Load() error
Render(io.Writer, string, interface{}, ...string) error
}
// AcquireCtx retrieves a new Ctx from the pool.
func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) *Ctx {
2020-09-13 11:20:11 +02:00
c := app.pool.Get().(*Ctx)
// Set app reference
2020-09-13 11:20:11 +02:00
c.app = app
// Reset route and handler index
2020-09-13 11:20:11 +02:00
c.indexRoute = -1
c.indexHandler = 0
// Reset matched flag
2020-09-13 11:20:11 +02:00
c.matched = false
// Set paths
2020-09-13 11:20:11 +02:00
c.pathBuffer = append(c.pathBuffer[0:0], fctx.URI().PathOriginal()...)
c.pathOriginal = getString(fctx.URI().PathOriginal())
// Set method
2020-09-13 11:20:11 +02:00
c.method = getString(fctx.Request.Header.Method())
c.methodINT = methodInt(c.method)
// Attach *fasthttp.RequestCtx to ctx
2020-09-13 11:20:11 +02:00
c.fasthttp = fctx
// Prettify path
2020-09-13 11:20:11 +02:00
c.prettifyPath()
return c
2020-02-21 18:07:43 +01:00
}
// ReleaseCtx releases the ctx back into the pool.
2020-09-13 11:20:11 +02:00
func (app *App) ReleaseCtx(c *Ctx) {
// Reset values
2020-09-13 11:20:11 +02:00
c.route = nil
c.fasthttp = nil
app.pool.Put(c)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Accepts checks if the specified extensions or content types are acceptable.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Accepts(offers ...string) string {
2020-02-21 18:07:43 +01:00
if len(offers) == 0 {
return ""
}
2020-09-13 11:20:11 +02:00
header := c.Get(HeaderAccept)
if header == "" {
2020-02-21 18:07:43 +01:00
return offers[0]
}
spec, commaPos := "", 0
for len(header) > 0 && commaPos != -1 {
commaPos = strings.IndexByte(header, ',')
if commaPos != -1 {
spec = utils.Trim(header[:commaPos], ' ')
} else {
spec = header
}
if factorSign := strings.IndexByte(spec, ';'); factorSign != -1 {
spec = spec[:factorSign]
}
2020-02-21 18:07:43 +01:00
for _, offer := range offers {
mimetype := utils.GetMIME(offer)
if len(spec) > 2 && spec[len(spec)-2:] == "/*" {
if strings.HasPrefix(spec[:len(spec)-2], strings.Split(mimetype, "/")[0]) {
return offer
} else if spec == "*/*" {
return offer
2020-02-21 18:07:43 +01:00
}
} else if strings.HasPrefix(spec, mimetype) {
return offer
2020-02-21 18:07:43 +01:00
}
}
if commaPos != -1 {
header = header[commaPos+1:]
}
2020-02-21 18:07:43 +01:00
}
2020-02-21 18:07:43 +01:00
return ""
}
2020-03-24 05:46:13 +01:00
// AcceptsCharsets checks if the specified charset is acceptable.
2020-09-13 11:20:11 +02:00
func (c *Ctx) AcceptsCharsets(offers ...string) string {
return getOffer(c.Get(HeaderAcceptCharset), offers...)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// AcceptsEncodings checks if the specified encoding is acceptable.
2020-09-13 11:20:11 +02:00
func (c *Ctx) AcceptsEncodings(offers ...string) string {
return getOffer(c.Get(HeaderAcceptEncoding), offers...)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// AcceptsLanguages checks if the specified language is acceptable.
2020-09-13 11:20:11 +02:00
func (c *Ctx) AcceptsLanguages(offers ...string) string {
return getOffer(c.Get(HeaderAcceptLanguage), offers...)
2020-02-21 18:07:43 +01:00
}
2020-09-13 11:20:11 +02:00
// App returns the *App reference to the instance of the Fiber application
func (c *Ctx) App() *App {
return c.app
2020-06-06 07:31:33 +02:00
}
2020-03-24 05:46:13 +01:00
// Append the specified value to the HTTP response header field.
2020-03-16 15:43:16 +01:00
// If the header is not already set, it creates the header with the specified value.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Append(field string, values ...string) {
2020-02-21 18:07:43 +01:00
if len(values) == 0 {
return
}
2020-09-13 11:20:11 +02:00
h := getString(c.fasthttp.Response.Header.Peek(field))
originalH := h
for _, value := range values {
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
if len(h) == 0 {
h = value
} else if h != value && !strings.HasPrefix(h, value+",") && !strings.HasSuffix(h, " "+value) &&
!strings.Contains(h, " "+value+",") {
h += ", " + value
2020-02-21 18:07:43 +01:00
}
}
if originalH != h {
2020-09-13 11:20:11 +02:00
c.Set(field, h)
}
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Attachment sets the HTTP response Content-Disposition header field to attachment.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Attachment(filename ...string) {
if len(filename) > 0 {
fname := filepath.Base(filename[0])
2020-09-13 11:20:11 +02:00
c.Type(filepath.Ext(fname))
2020-09-13 11:20:11 +02:00
c.setCanonical(HeaderContentDisposition, `attachment; filename="`+quoteString(fname)+`"`)
2020-02-21 18:07:43 +01:00
return
}
2020-09-13 11:20:11 +02:00
c.setCanonical(HeaderContentDisposition, "attachment")
2020-02-21 18:07:43 +01:00
}
// BaseURL returns (protocol + host + base path).
2020-09-13 11:20:11 +02:00
func (c *Ctx) BaseURL() string {
2020-07-02 13:51:10 +02:00
// TODO: Could be improved: 53.8 ns/op 32 B/op 1 allocs/op
// Should work like https://codeigniter.com/user_guide/helpers/url_helper.html
2020-09-13 11:20:11 +02:00
return c.Protocol() + "://" + c.Hostname()
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Body contains the raw body submitted in a POST request.
2020-05-31 01:34:16 +02:00
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Body() []byte {
return c.fasthttp.Request.Body()
2020-02-21 18:07:43 +01:00
}
// decoderPool helps to improve BodyParser's and QueryParser's performance
var decoderPool = &sync.Pool{New: func() interface{} {
var decoder = schema.NewDecoder()
decoder.IgnoreUnknownKeys(true)
return decoder
}}
2020-03-24 05:46:13 +01:00
// BodyParser binds the request body to a struct.
// It supports decoding the following content types based on the Content-Type header:
2020-03-16 15:43:16 +01:00
// application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data
2020-09-13 11:20:11 +02:00
func (c *Ctx) BodyParser(out interface{}) error {
// Get decoder from pool
schemaDecoder := decoderPool.Get().(*schema.Decoder)
defer decoderPool.Put(schemaDecoder)
// Get content-type
2020-09-13 11:20:11 +02:00
ctype := getString(c.fasthttp.Request.Header.ContentType())
// Parse body accordingly
if strings.HasPrefix(ctype, MIMEApplicationJSON) {
schemaDecoder.SetAliasTag("json")
2020-09-13 11:20:11 +02:00
return json.Unmarshal(c.fasthttp.Request.Body(), out)
} else if strings.HasPrefix(ctype, MIMEApplicationForm) {
schemaDecoder.SetAliasTag("form")
2020-07-15 14:22:31 +08:00
data := make(map[string][]string)
2020-09-13 11:20:11 +02:00
c.fasthttp.PostArgs().VisitAll(func(key []byte, val []byte) {
2020-07-15 14:22:31 +08:00
data[getString(key)] = append(data[getString(key)], getString(val))
})
return schemaDecoder.Decode(out, data)
} else if strings.HasPrefix(ctype, MIMEMultipartForm) {
schemaDecoder.SetAliasTag("form")
2020-09-13 11:20:11 +02:00
data, err := c.fasthttp.MultipartForm()
2020-02-21 18:07:43 +01:00
if err != nil {
return err
}
return schemaDecoder.Decode(out, data.Value)
} else if strings.HasPrefix(ctype, MIMETextXML) || strings.HasPrefix(ctype, MIMEApplicationXML) {
schemaDecoder.SetAliasTag("xml")
2020-09-13 11:20:11 +02:00
return xml.Unmarshal(c.fasthttp.Request.Body(), out)
2020-02-21 18:07:43 +01:00
}
// No suitable content type found
2020-06-08 02:55:19 +02:00
return fmt.Errorf("bodyparser: cannot parse content-type: %v", ctype)
2020-02-21 18:07:43 +01:00
}
// ClearCookie expires a specific cookie by key on the client side.
// If no key is provided it expires all cookies that came with the request.
2020-09-13 11:20:11 +02:00
func (c *Ctx) ClearCookie(key ...string) {
2020-02-26 19:31:43 -05:00
if len(key) > 0 {
for i := range key {
2020-09-13 11:20:11 +02:00
c.fasthttp.Response.Header.DelClientCookie(key[i])
2020-02-21 18:07:43 +01:00
}
return
}
2020-09-13 11:20:11 +02:00
c.fasthttp.Request.Header.VisitAllCookie(func(k, v []byte) {
c.fasthttp.Response.Header.DelClientCookieBytes(k)
2020-02-21 18:07:43 +01:00
})
}
2020-09-13 11:20:11 +02:00
// Context returns *fasthttp.RequestCtx that carries a deadline
// a cancellation signal, and other values across API boundaries.
func (c *Ctx) Context() *fasthttp.RequestCtx {
return c.fasthttp
}
// Cookie sets a cookie by passing a cookie struct.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Cookie(cookie *Cookie) {
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
fcookie := fasthttp.AcquireCookie()
2020-02-26 19:31:43 -05:00
fcookie.SetKey(cookie.Name)
fcookie.SetValue(cookie.Value)
fcookie.SetPath(cookie.Path)
fcookie.SetDomain(cookie.Domain)
2020-09-30 15:31:46 +02:00
fcookie.SetMaxAge(cookie.MaxAge)
2020-02-26 19:31:43 -05:00
fcookie.SetExpire(cookie.Expires)
fcookie.SetSecure(cookie.Secure)
fcookie.SetHTTPOnly(cookie.HTTPOnly)
switch utils.ToLower(cookie.SameSite) {
2020-03-20 16:43:28 +01:00
case "strict":
fcookie.SetSameSite(fasthttp.CookieSameSiteStrictMode)
case "none":
fcookie.SetSameSite(fasthttp.CookieSameSiteNoneMode)
default:
fcookie.SetSameSite(fasthttp.CookieSameSiteLaxMode)
2020-03-20 16:43:28 +01:00
}
2020-09-13 11:20:11 +02:00
c.fasthttp.Response.Header.SetCookie(fcookie)
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
fasthttp.ReleaseCookie(fcookie)
2020-02-21 18:07:43 +01:00
}
// Cookies is used for getting a cookie value by key.
// Defaults to the empty string "" if the cookie doesn't exist.
// If a default value is given, it will return that value if the cookie doesn't exist.
// The returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting to use the value outside the Handler.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Cookies(key string, defaultValue ...string) string {
return defaultString(getString(c.fasthttp.Request.Header.Cookie(key)), defaultValue)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Download transfers the file from path as an attachment.
2020-03-16 15:43:16 +01:00
// Typically, browsers will prompt the user for download.
// By default, the Content-Disposition header filename= parameter is the filepath (this typically appears in the browser dialog).
// Override this default with the filename parameter.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Download(file string, filename ...string) error {
var fname string
if len(filename) > 0 {
fname = filename[0]
2020-09-13 11:20:11 +02:00
} else {
fname = filepath.Base(file)
2020-02-21 18:07:43 +01:00
}
2020-09-13 11:20:11 +02:00
c.setCanonical(HeaderContentDisposition, `attachment; filename="`+quoteString(fname)+`"`)
return c.SendFile(file)
2020-02-21 18:07:43 +01:00
}
2020-09-13 11:20:11 +02:00
// Request return the *fasthttp.Request object
// This allows you to use all fasthttp request methods
// https://godoc.org/github.com/valyala/fasthttp#Request
func (c *Ctx) Request() *fasthttp.Request {
return &c.fasthttp.Request
}
2020-09-13 11:39:55 +02:00
// Response return the *fasthttp.Response object
2020-09-13 11:20:11 +02:00
// This allows you to use all fasthttp response methods
// https://godoc.org/github.com/valyala/fasthttp#Response
func (c *Ctx) Response() *fasthttp.Response {
return &c.fasthttp.Response
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Format performs content-negotiation on the Accept HTTP header.
// It uses Accepts to select a proper format.
2020-03-16 15:43:16 +01:00
// If the header is not specified or there is no proper format, text/plain is used.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Format(body interface{}) error {
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
// Get accepted content type
2020-09-13 11:20:11 +02:00
accept := c.Accepts("html", "json", "txt", "xml")
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
// Set accepted content type
2020-09-13 11:20:11 +02:00
c.Type(accept)
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
// Type convert provided body
var b string
2020-02-26 19:31:43 -05:00
switch val := body.(type) {
case string:
b = val
case []byte:
b = getString(val)
default:
b = fmt.Sprintf("%v", val)
}
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
// Format based on the accept content type
2020-02-26 19:31:43 -05:00
switch accept {
case "html":
2020-09-13 11:20:11 +02:00
return c.SendString("<p>" + b + "</p>")
2020-02-26 19:31:43 -05:00
case "json":
2020-09-13 11:20:11 +02:00
return c.JSON(body)
2020-07-14 15:24:24 +08:00
case "txt":
2020-09-13 11:20:11 +02:00
return c.SendString(b)
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
case "xml":
raw, err := xml.Marshal(body)
if err != nil {
2020-09-13 11:20:11 +02:00
return fmt.Errorf("error serializing xml: %v", body)
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
}
2020-09-13 11:20:11 +02:00
c.fasthttp.Response.SetBody(raw)
return nil
2020-02-21 18:07:43 +01:00
}
2020-09-13 11:20:11 +02:00
return c.SendString(b)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// FormFile returns the first file by key from a MultipartForm.
2020-09-13 11:20:11 +02:00
func (c *Ctx) FormFile(key string) (*multipart.FileHeader, error) {
return c.fasthttp.FormFile(key)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// FormValue returns the first value by key from a MultipartForm.
2020-09-14 04:54:26 +02:00
// Defaults to the empty string "" if the form value doesn't exist.
// If a default value is given, it will return that value if the form value does not exist.
2020-05-31 01:34:16 +02:00
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
2020-09-13 11:20:11 +02:00
func (c *Ctx) FormValue(key string, defaultValue ...string) string {
return defaultString(getString(c.fasthttp.FormValue(key)), defaultValue)
2020-02-21 18:07:43 +01:00
}
// Fresh returns true when the response is still “fresh” in the client's cache,
// otherwise false is returned to indicate that the client cache is now stale
// and the full response should be sent.
// When a client sends the Cache-Control: no-cache request header to indicate an end-to-end
// reload request, this module will return false to make handling these requests transparent.
// https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33
2020-09-13 11:20:11 +02:00
func (c *Ctx) Fresh() bool {
// fields
2020-09-13 11:20:11 +02:00
var modifiedSince = c.Get(HeaderIfModifiedSince)
var noneMatch = c.Get(HeaderIfNoneMatch)
// unconditional request
if modifiedSince == "" && noneMatch == "" {
return false
}
// Always return stale when Cache-Control: no-cache
// to support end-to-end reload requests
// https://tools.ietf.org/html/rfc2616#section-14.9.4
2020-09-13 11:20:11 +02:00
cacheControl := c.Get(HeaderCacheControl)
if cacheControl != "" && isNoCache(cacheControl) {
return false
}
// if-none-match
if noneMatch != "" && noneMatch != "*" {
2020-09-13 11:20:11 +02:00
var etag = getString(c.fasthttp.Response.Header.Peek(HeaderETag))
if etag == "" {
return false
}
2020-07-26 17:48:24 -07:00
if isEtagStale(etag, getBytes(noneMatch)) {
return false
}
if modifiedSince != "" {
2020-09-13 11:20:11 +02:00
var lastModified = getString(c.fasthttp.Response.Header.Peek(HeaderLastModified))
if lastModified != "" {
lastModifiedTime, err := http.ParseTime(lastModified)
if err != nil {
return false
}
modifiedSinceTime, err := http.ParseTime(modifiedSince)
if err != nil {
return false
}
return lastModifiedTime.Before(modifiedSinceTime)
}
}
}
return true
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Get returns the HTTP request header specified by field.
2020-03-16 15:43:16 +01:00
// Field names are case-insensitive
2020-05-31 01:34:16 +02:00
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Get(key string, defaultValue ...string) string {
return defaultString(getString(c.fasthttp.Request.Header.Peek(key)), defaultValue)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Hostname contains the hostname derived from the Host HTTP header.
2020-05-31 01:34:16 +02:00
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Hostname() string {
return getString(c.fasthttp.Request.URI().Host())
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// IP returns the remote IP address of the request.
2020-09-13 11:20:11 +02:00
func (c *Ctx) IP() string {
if len(c.app.config.ProxyHeader) > 0 {
return c.Get(c.app.config.ProxyHeader)
}
return c.fasthttp.RemoteIP().String()
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// IPs returns an string slice of IP addresses specified in the X-Forwarded-For request header.
2020-09-13 11:20:11 +02:00
func (c *Ctx) IPs() (ips []string) {
header := c.fasthttp.Request.Header.Peek(HeaderXForwardedFor)
if len(header) == 0 {
return
}
2020-07-15 15:59:10 +08:00
ips = make([]string, bytes.Count(header, []byte(","))+1)
var commaPos, i int
for {
commaPos = bytes.IndexByte(header, ',')
if commaPos != -1 {
2020-09-13 11:20:11 +02:00
ips[i] = utils.Trim(getString(header[:commaPos]), ' ')
header, i = header[commaPos+1:], i+1
2020-07-15 15:59:10 +08:00
} else {
2020-09-13 11:20:11 +02:00
ips[i] = utils.Trim(getString(header), ' ')
2020-07-15 15:59:10 +08:00
return
}
2020-02-21 18:07:43 +01:00
}
}
2020-03-24 05:46:13 +01:00
// Is returns the matching content type,
// if the incoming request's Content-Type HTTP header field matches the MIME type specified by the type parameter
2020-09-13 11:20:11 +02:00
func (c *Ctx) Is(extension string) bool {
extensionHeader := utils.GetMIME(extension)
if extensionHeader == "" {
return false
2020-02-21 18:07:43 +01:00
}
2020-07-21 21:09:51 +02:00
return strings.HasPrefix(
2020-09-27 12:22:17 +02:00
utils.TrimLeft(utils.UnsafeString(c.fasthttp.Request.Header.ContentType()), ' '),
2020-07-21 21:09:51 +02:00
extensionHeader,
)
2020-02-21 18:07:43 +01:00
}
2020-07-11 10:06:35 +08:00
// JSON converts any interface or string to JSON.
2020-03-16 15:43:16 +01:00
// This method also sets the content header to application/json.
2020-09-13 11:20:11 +02:00
func (c *Ctx) JSON(data interface{}) error {
raw, err := json.Marshal(data)
2020-04-23 00:33:36 +02:00
if err != nil {
return err
2020-03-24 03:36:52 +01:00
}
2020-09-13 11:20:11 +02:00
c.fasthttp.Response.SetBodyRaw(raw)
c.fasthttp.Response.Header.SetContentType(MIMEApplicationJSON)
2020-02-21 18:07:43 +01:00
return nil
}
2020-03-24 05:46:13 +01:00
// JSONP sends a JSON response with JSONP support.
2020-03-16 15:43:16 +01:00
// This method is identical to JSON, except that it opts-in to JSONP callback support.
// By default, the callback name is simply callback.
2020-09-13 11:20:11 +02:00
func (c *Ctx) JSONP(data interface{}, callback ...string) error {
raw, err := json.Marshal(data)
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
2020-04-23 00:33:36 +02:00
if err != nil {
return err
2020-02-21 18:07:43 +01:00
}
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
var result, cb string
2020-02-26 19:31:43 -05:00
if len(callback) > 0 {
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
cb = callback[0]
} else {
cb = "callback"
2020-02-21 18:07:43 +01:00
}
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
result = cb + "(" + getString(raw) + ");"
2020-09-13 11:20:11 +02:00
c.setCanonical(HeaderXContentTypeOptions, "nosniff")
c.fasthttp.Response.Header.SetContentType(MIMEApplicationJavaScriptCharsetUTF8)
return c.SendString(result)
2020-02-21 18:07:43 +01:00
}
// Links joins the links followed by the property to populate the response's Link HTTP header field.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Links(link ...string) {
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
if len(link) == 0 {
return
}
bb := bytebufferpool.Get()
for i := range link {
2020-02-21 18:07:43 +01:00
if i%2 == 0 {
2020-05-16 05:22:49 +02:00
_ = bb.WriteByte('<')
_, _ = bb.WriteString(link[i])
_ = bb.WriteByte('>')
2020-02-21 18:07:43 +01:00
} else {
2020-05-16 05:22:49 +02:00
_, _ = bb.WriteString(`; rel="` + link[i] + `",`)
2020-02-21 18:07:43 +01:00
}
}
2020-09-13 11:20:11 +02:00
c.setCanonical(HeaderLink, utils.TrimRight(getString(bb.Bytes()), ','))
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
bytebufferpool.Put(bb)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Locals makes it possible to pass interface{} values under string keys scoped to the request
// and therefore available to all following routes that match the request.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Locals(key string, value ...interface{}) (val interface{}) {
2020-02-26 19:31:43 -05:00
if len(value) == 0 {
2020-09-13 11:20:11 +02:00
return c.fasthttp.UserValue(key)
2020-02-21 18:07:43 +01:00
}
2020-09-13 11:20:11 +02:00
c.fasthttp.SetUserValue(key, value[0])
2020-02-26 19:31:43 -05:00
return value[0]
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Location sets the response Location HTTP header to the specified path parameter.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Location(path string) {
c.setCanonical(HeaderLocation, path)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Method contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Method(override ...string) string {
2020-03-16 15:00:58 +01:00
if len(override) > 0 {
method := utils.ToUpper(override[0])
2020-06-30 00:27:28 +02:00
mINT := methodInt(method)
2020-07-13 16:47:15 +08:00
if mINT == -1 {
2020-09-13 11:20:11 +02:00
return c.method
}
2020-09-13 11:20:11 +02:00
c.method = method
c.methodINT = mINT
2020-03-16 15:00:58 +01:00
}
2020-09-13 11:20:11 +02:00
return c.method
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// MultipartForm parse form entries from binary.
2020-03-16 15:43:16 +01:00
// This returns a map[string][]string, so given a key the value will be a string slice.
2020-09-13 11:20:11 +02:00
func (c *Ctx) MultipartForm() (*multipart.Form, error) {
return c.fasthttp.MultipartForm()
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Next executes the next method in the stack that matches the current route.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Next() (err error) {
// Increment handler index
2020-09-13 11:20:11 +02:00
c.indexHandler++
// Did we executed all route handlers?
2020-09-13 11:20:11 +02:00
if c.indexHandler < len(c.route.Handlers) {
// Continue route stack
err = c.route.Handlers[c.indexHandler](c)
} else {
// Continue handler stack
2020-09-13 11:20:11 +02:00
_, err = c.app.next(c)
}
return err
2020-02-21 18:07:43 +01:00
}
2020-09-14 09:24:48 +02:00
// OriginalURL contains the original request URL.
2020-05-31 01:34:16 +02:00
// Returned value is only valid within the handler. Do not store any references.
2020-07-13 15:37:38 +02:00
// Make copies or use the Immutable setting to use the value outside the Handler.
2020-09-13 11:20:11 +02:00
func (c *Ctx) OriginalURL() string {
return getString(c.fasthttp.Request.Header.RequestURI())
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Params is used to get the route parameters.
// Defaults to empty string "" if the param doesn't exist.
// If a default value is given, it will return that value if the param doesn't exist.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting to use the value outside the Handler.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Params(key string, defaultValue ...string) string {
2020-08-09 19:50:10 +02:00
if key == "*" || key == "+" {
key += "1"
}
2020-09-13 11:20:11 +02:00
for i := range c.route.Params {
if len(key) != len(c.route.Params[i]) {
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
continue
}
2020-09-13 11:20:11 +02:00
if c.route.Params[i] == key {
2020-05-24 08:47:47 +02:00
// in case values are not here
2020-09-13 11:20:11 +02:00
if len(c.values) <= i || len(c.values[i]) == 0 {
2020-07-03 19:30:34 +02:00
break
2020-05-23 23:33:28 -04:00
}
2020-09-13 11:20:11 +02:00
return c.values[i]
2020-02-21 18:07:43 +01:00
}
}
2020-07-04 10:11:23 +02:00
return defaultString("", defaultValue)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Path returns the path part of the request URL.
2020-03-16 15:00:58 +01:00
// Optionally, you could override the path.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Path(override ...string) string {
if len(override) != 0 && c.path != override[0] {
// Set new path to context
2020-09-13 11:20:11 +02:00
c.pathBuffer = append(c.pathBuffer[0:0], override[0]...)
c.pathOriginal = override[0]
// c.path = override[0]
// c.pathOriginal = c.path
// Set new path to request context
2020-09-13 11:20:11 +02:00
c.fasthttp.Request.URI().SetPath(c.pathOriginal)
// Prettify path
2020-09-13 11:20:11 +02:00
c.prettifyPath()
2020-03-16 15:00:58 +01:00
}
2020-09-13 11:20:11 +02:00
return c.pathOriginal
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Protocol contains the request protocol string: http or https for TLS requests.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Protocol() string {
if c.fasthttp.IsTLS() {
2020-02-21 18:07:43 +01:00
return "https"
}
scheme := "http"
2020-09-13 11:20:11 +02:00
c.fasthttp.Request.Header.VisitAll(func(key, val []byte) {
if len(key) < 12 {
return // X-Forwarded-
} else if bytes.HasPrefix(key, []byte("X-Forwarded-")) {
if bytes.Equal(key, []byte(HeaderXForwardedProto)) {
scheme = getString(val)
} else if bytes.Equal(key, []byte(HeaderXForwardedProtocol)) {
scheme = getString(val)
} else if bytes.Equal(key, []byte(HeaderXForwardedSsl)) && bytes.Equal(val, []byte("on")) {
scheme = "https"
}
} else if bytes.Equal(key, []byte(HeaderXUrlScheme)) {
scheme = getString(val)
}
})
return scheme
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Query returns the query string parameter in the url.
// Defaults to empty string "" if the query doesn't exist.
// If a default value is given, it will return that value if the query doesn't exist.
2020-05-31 01:34:16 +02:00
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting to use the value outside the Handler.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Query(key string, defaultValue ...string) string {
return defaultString(getString(c.fasthttp.QueryArgs().Peek(key)), defaultValue)
}
// QueryParser binds the query string to a struct.
func (c *Ctx) QueryParser(out interface{}) error {
if c.fasthttp.QueryArgs().Len() < 1 {
return nil
}
// Get decoder from pool
var decoder = decoderPool.Get().(*schema.Decoder)
defer decoderPool.Put(decoder)
// Set correct alias tag
decoder.SetAliasTag("query")
data := make(map[string][]string)
c.fasthttp.QueryArgs().VisitAll(func(key []byte, val []byte) {
2020-09-27 12:22:17 +02:00
k := utils.UnsafeString(key)
v := utils.UnsafeString(val)
if strings.Contains(v, ",") && equalFieldType(out, reflect.Slice, k) {
values := strings.Split(v, ",")
for i := 0; i < len(values); i++ {
data[k] = append(data[k], values[i])
}
} else {
data[k] = append(data[k], v)
}
2020-09-13 11:20:11 +02:00
})
return decoder.Decode(out, data)
2020-02-21 18:07:43 +01:00
}
func equalFieldType(out interface{}, kind reflect.Kind, key string) bool {
// Get type of interface
outTyp := reflect.TypeOf(out).Elem()
// Must be a struct to match a field
if outTyp.Kind() != reflect.Struct {
return false
}
// Copy interface to an value to be used
outVal := reflect.ValueOf(out).Elem()
// Loop over each field
for i := 0; i < outTyp.NumField(); i++ {
// Get field value data
structField := outVal.Field(i)
// Can this field be changed?
if !structField.CanSet() {
continue
}
// Get field key data
typeField := outTyp.Field(i)
// Get type of field key
structFieldKind := structField.Kind()
// Does the field type equals input?
if structFieldKind != kind {
continue
}
// Get tag from field if exist
inputFieldName := typeField.Tag.Get(key)
if inputFieldName == "" {
inputFieldName = typeField.Name
}
// Compare field/tag with provided key
if utils.ToLower(inputFieldName) == key {
return true
}
}
return false
}
2020-07-14 15:24:24 +08:00
var (
ErrRangeMalformed = errors.New("range: malformed range header string")
ErrRangeUnsatisfiable = errors.New("range: unsatisfiable range")
)
2020-03-24 05:46:13 +01:00
// Range returns a struct containing the type and a slice of ranges.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Range(size int) (rangeData Range, err error) {
rangeStr := c.Get(HeaderRange)
2020-02-29 21:12:17 +08:00
if rangeStr == "" || !strings.Contains(rangeStr, "=") {
2020-07-14 15:24:24 +08:00
err = ErrRangeMalformed
return
2020-02-29 21:00:54 +08:00
}
data := strings.Split(rangeStr, "=")
2020-07-14 15:24:24 +08:00
if len(data) != 2 {
err = ErrRangeMalformed
return
}
rangeData.Type = data[0]
2020-02-29 21:00:54 +08:00
arr := strings.Split(data[1], ",")
for i := 0; i < len(arr); i++ {
item := strings.Split(arr[i], "-")
if len(item) == 1 {
2020-07-14 15:24:24 +08:00
err = ErrRangeMalformed
return
2020-02-29 21:00:54 +08:00
}
start, startErr := strconv.Atoi(item[0])
end, endErr := strconv.Atoi(item[1])
2020-02-29 21:00:54 +08:00
if startErr != nil { // -nnn
start = size - end
end = size - 1
} else if endErr != nil { // nnn-
end = size - 1
}
if end > size-1 { // limit last-byte-pos to current length
end = size - 1
}
if start > end || start < 0 {
continue
}
rangeData.Ranges = append(rangeData.Ranges, struct {
Start int
End int
2020-02-29 21:00:54 +08:00
}{
start,
end,
})
}
if len(rangeData.Ranges) < 1 {
2020-07-14 15:24:24 +08:00
err = ErrRangeUnsatisfiable
return
2020-02-29 21:00:54 +08:00
}
2020-07-14 15:24:24 +08:00
return
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Redirect to the URL derived from the specified path, with specified status.
// If status is not specified, status defaults to 302 Found.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Redirect(location string, status ...int) error {
c.setCanonical(HeaderLocation, location)
2020-02-21 18:07:43 +01:00
if len(status) > 0 {
2020-09-13 11:20:11 +02:00
c.Status(status[0])
Use param support + optimizations (#361) * Benchmark workflow * Update router.go * Clean root * Add mutex * Benchmark workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Benchmark Workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Update security workflow * Benchmark workflow * Add mutex * Enable benchmark tests * Enable race testing Co-Authored-By: ReneWerner87 <renewerner87@users.noreply.github.com> * Make Ctx pool accessible - Add ctx benchmarks * v1.9.6 * v1.9.6 Co-Authored-By: ReneWerner87 <renewerner87@googlemail.com> * Improve context functions * Add utils benchmarks * Update benchmarks & tests * Add utils tests * New tests * update test * Move fastpath tests * offer negotiation * Cleanup * Update Vary Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize Append Co-Authored-By: RW <renewerner87@googlemail.com> * Optimize more methods Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add param support to Use Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Add use_params tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * Tests Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> * v1.9.7 Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Update app_test.go Co-Authored-By: RW <renewerner87@googlemail.com> Co-Authored-By: Vic Shóstak <vikkyshostak@gmail.com> Co-Authored-By: József Sallai <jozsef@sallai.me> Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-Authored-By: Nifty255 <nifty255@users.noreply.github.com> * Rename argument Co-Authored-By: RW <renewerner87@googlemail.com> * Add nosec for WriteByte Co-Authored-By: RW <renewerner87@googlemail.com> * Add media article * Update media articles * Fix typo Co-Authored-By: Thomas van Vugt <thomasvvugt@users.noreply.github.com> * Fix typo Co-authored-by: ReneWerner87 <renewerner87@users.noreply.github.com> Co-authored-by: ReneWerner87 <renewerner87@googlemail.com> Co-authored-by: Vic Shóstak <vikkyshostak@gmail.com> Co-authored-by: József Sallai <jozsef@sallai.me> Co-authored-by: Thomas van Vugt <thomasvvugt@users.noreply.github.com> Co-authored-by: Nifty255 <nifty255@users.noreply.github.com>
2020-05-12 19:24:04 +02:00
} else {
2020-09-13 11:20:11 +02:00
c.Status(StatusFound)
2020-02-21 18:07:43 +01:00
}
2020-09-13 11:20:11 +02:00
return nil
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Render a template with data and sends a text/html response.
2020-03-16 15:29:53 +01:00
// We support the following engines: html, amber, handlebars, mustache, pug
2020-09-13 11:20:11 +02:00
func (c *Ctx) Render(name string, bind interface{}, layouts ...string) error {
var err error
// Get new buffer from pool
buf := bytebufferpool.Get()
defer bytebufferpool.Put(buf)
2020-09-13 11:20:11 +02:00
if c.app.config.Views != nil {
2020-06-12 12:29:57 +02:00
// Render template from Views
2020-09-13 11:20:11 +02:00
if err := c.app.config.Views.Render(buf, name, bind, layouts...); err != nil {
2020-06-12 12:29:57 +02:00
return err
}
2020-03-22 20:31:58 +01:00
} else {
// Render raw template using 'name' as filepath if no engine is set
2020-03-22 20:31:58 +01:00
var tmpl *template.Template
2020-07-29 11:07:47 +08:00
if _, err = readContent(buf, name); err != nil {
return err
}
// Parse template
if tmpl, err = template.New("").Parse(getString(buf.Bytes())); err != nil {
2020-02-21 18:07:43 +01:00
return err
}
2020-06-07 22:34:29 +02:00
buf.Reset()
// Render template
if err = tmpl.Execute(buf, bind); err != nil {
2020-02-21 18:07:43 +01:00
return err
}
}
2020-07-15 15:59:10 +08:00
// Set Content-Type to text/html
2020-09-13 11:20:11 +02:00
c.fasthttp.Response.Header.SetContentType(MIMETextHTMLCharsetUTF8)
// Set rendered template to body
2020-09-13 11:20:11 +02:00
c.fasthttp.Response.SetBody(buf.Bytes())
// Return err if exist
2020-09-13 11:20:11 +02:00
return err
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Route returns the matched Route struct.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Route() *Route {
if c.route == nil {
2020-06-07 10:13:50 +02:00
// Fallback for fasthttp error handler
return &Route{
2020-09-13 11:20:11 +02:00
path: c.pathOriginal,
Path: c.pathOriginal,
Method: c.method,
2020-06-07 10:13:50 +02:00
Handlers: make([]Handler, 0),
2020-09-13 11:20:11 +02:00
Params: make([]string, 0),
2020-06-07 10:13:50 +02:00
}
}
2020-09-13 11:20:11 +02:00
return c.route
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// SaveFile saves any multipart file to disk.
2020-09-13 11:20:11 +02:00
func (c *Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error {
2020-02-26 19:31:43 -05:00
return fasthttp.SaveMultipartFile(fileheader, path)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Secure returns a boolean property, that is true, if a TLS connection is established.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Secure() bool {
return c.fasthttp.IsTLS()
2020-02-21 18:07:43 +01:00
}
2020-09-13 11:20:11 +02:00
// Send sets the HTTP response body without copying it.
// From this point onward the body argument must not be changed.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Send(body []byte) error {
// Write response body
c.fasthttp.Response.SetBodyRaw(body)
return nil
2020-02-21 18:07:43 +01:00
}
2020-09-13 11:20:11 +02:00
var sendFileOnce sync.Once
2020-06-06 07:31:33 +02:00
var sendFileFS *fasthttp.FS
var sendFileHandler fasthttp.RequestHandler
2020-03-24 05:46:13 +01:00
// SendFile transfers the file from the given path.
2020-06-06 07:31:33 +02:00
// The file is not compressed by default, enable this by passing a 'true' argument
2020-03-16 15:29:53 +01:00
// Sets the Content-Type response HTTP header field based on the filenames extension.
2020-09-13 11:20:11 +02:00
func (c *Ctx) SendFile(file string, compress ...bool) error {
2020-10-09 23:11:44 -04:00
// Save the filename, we will need it in the error message if the file isn't found
filename := file
2020-06-06 07:31:33 +02:00
// https://github.com/valyala/fasthttp/blob/master/fs.go#L81
2020-09-13 11:20:11 +02:00
sendFileOnce.Do(func() {
2020-06-06 07:31:33 +02:00
sendFileFS = &fasthttp.FS{
Root: "/",
GenerateIndexPages: false,
AcceptByteRange: true,
Compress: true,
2020-09-13 11:20:11 +02:00
CompressedFileSuffix: c.app.config.CompressedFileSuffix,
2020-06-06 07:31:33 +02:00
CacheDuration: 10 * time.Second,
IndexNames: []string{"index.html"},
2020-06-08 02:45:48 +02:00
PathNotFound: func(ctx *fasthttp.RequestCtx) {
ctx.Response.SetStatusCode(StatusNotFound)
2020-06-08 02:45:48 +02:00
},
2020-06-06 07:31:33 +02:00
}
sendFileHandler = sendFileFS.NewRequestHandler()
2020-07-16 09:00:20 +08:00
})
// Keep original path for mutable params
2020-09-27 12:22:17 +02:00
c.pathOriginal = utils.SafeString(c.pathOriginal)
2020-06-06 07:31:33 +02:00
// Disable compression
if len(compress) <= 0 || !compress[0] {
// https://github.com/valyala/fasthttp/blob/master/fs.go#L46
2020-09-13 11:20:11 +02:00
c.fasthttp.Request.Header.Del(HeaderAcceptEncoding)
2020-06-06 07:31:33 +02:00
}
// https://github.com/valyala/fasthttp/blob/master/fs.go#L85
if len(file) == 0 || file[0] != '/' {
hasTrailingSlash := len(file) > 0 && file[len(file)-1] == '/'
var err error
if file, err = filepath.Abs(file); err != nil {
2020-06-08 02:45:48 +02:00
return err
2020-06-06 07:31:33 +02:00
}
if hasTrailingSlash {
file += "/"
}
2020-02-21 18:07:43 +01:00
}
2020-07-15 15:59:10 +08:00
// Set new URI for fileHandler
2020-09-13 11:20:11 +02:00
c.fasthttp.Request.SetRequestURI(file)
2020-06-06 07:31:33 +02:00
// Save status code
2020-09-13 11:20:11 +02:00
status := c.fasthttp.Response.StatusCode()
2020-06-06 07:31:33 +02:00
// Serve file
2020-09-13 11:20:11 +02:00
sendFileHandler(c.fasthttp)
// Get the status code which is set by fasthttp
2020-09-13 11:20:11 +02:00
fsStatus := c.fasthttp.Response.StatusCode()
// Set the status code set by the user if it is different from the fasthttp status code and 200
if status != fsStatus && status != StatusOK {
2020-09-13 11:20:11 +02:00
c.Status(status)
}
2020-06-08 02:45:48 +02:00
// Check for error
if status != StatusNotFound && fsStatus == StatusNotFound {
2020-10-09 23:11:44 -04:00
return NewError(StatusNotFound, fmt.Sprintf("sendfile: file %s not found", filename))
2020-06-08 02:45:48 +02:00
}
return nil
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// SendStatus sets the HTTP status code and if the response body is empty,
2020-03-16 15:29:53 +01:00
// it sets the correct status message in the body.
2020-09-13 11:20:11 +02:00
func (c *Ctx) SendStatus(status int) error {
c.Status(status)
2020-02-21 18:07:43 +01:00
// Only set status body when there is no response body
2020-09-13 11:20:11 +02:00
if len(c.fasthttp.Response.Body()) == 0 {
return c.SendString(utils.StatusMessage(status))
2020-02-21 18:07:43 +01:00
}
2020-09-13 11:20:11 +02:00
return nil
2020-02-21 18:07:43 +01:00
}
// SendString sets the HTTP response body for string types.
2020-03-16 15:29:53 +01:00
// This means no type assertion, recommended for faster performance
2020-09-13 11:20:11 +02:00
func (c *Ctx) SendString(body string) error {
c.fasthttp.Response.SetBodyString(body)
return nil
2020-02-21 18:07:43 +01:00
}
// SendStream sets response body stream and optional body size.
2020-09-13 11:20:11 +02:00
func (c *Ctx) SendStream(stream io.Reader, size ...int) error {
if len(size) > 0 && size[0] >= 0 {
2020-09-13 11:20:11 +02:00
c.fasthttp.Response.SetBodyStream(stream, size[0])
} else {
2020-09-13 11:20:11 +02:00
c.fasthttp.Response.SetBodyStream(stream, -1)
c.setCanonical(HeaderContentLength, strconv.Itoa(len(c.fasthttp.Response.Body())))
}
2020-09-13 11:20:11 +02:00
return nil
}
// Set sets the response's HTTP header field to the specified key, value.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Set(key string, val string) {
c.fasthttp.Response.Header.Set(key, removeNewLines(val))
}
func (c *Ctx) setCanonical(key string, val string) {
2020-09-27 12:22:17 +02:00
c.fasthttp.Response.Header.SetCanonical(utils.UnsafeBytes(key), utils.UnsafeBytes(val))
2020-02-21 18:07:43 +01:00
}
2020-04-24 19:00:37 +02:00
// Subdomains returns a string slice of subdomains in the domain name of the request.
2020-03-16 15:29:53 +01:00
// The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Subdomains(offset ...int) []string {
2020-02-21 18:07:43 +01:00
o := 2
if len(offset) > 0 {
o = offset[0]
}
2020-09-13 11:20:11 +02:00
subdomains := strings.Split(c.Hostname(), ".")
l := len(subdomains) - o
// Check index to avoid slice bounds out of range panic
if l < 0 {
l = len(subdomains)
}
subdomains = subdomains[:l]
2020-02-26 19:31:43 -05:00
return subdomains
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Stale is not implemented yet, pull requests are welcome!
2020-09-13 11:20:11 +02:00
func (c *Ctx) Stale() bool {
return !c.Fresh()
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Status sets the HTTP status for the response.
2020-03-16 15:29:53 +01:00
// This method is chainable.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Status(status int) *Ctx {
c.fasthttp.Response.SetStatusCode(status)
return c
}
// String returns unique string representation of the ctx.
//
// The returned value may be useful for logging.
func (c *Ctx) String() string {
return fmt.Sprintf(
"#%016X - %s <-> %s - %s %s",
c.fasthttp.ID(),
c.fasthttp.LocalAddr(),
c.fasthttp.RemoteAddr(),
c.fasthttp.Request.Header.Method(),
c.fasthttp.URI().FullURI(),
)
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Type sets the Content-Type HTTP header to the MIME type specified by the file extension.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Type(extension string, charset ...string) *Ctx {
2020-06-06 07:31:33 +02:00
if len(charset) > 0 {
2020-09-13 11:20:11 +02:00
c.fasthttp.Response.Header.SetContentType(utils.GetMIME(extension) + "; charset=" + charset[0])
2020-06-06 07:31:33 +02:00
} else {
2020-09-13 11:20:11 +02:00
c.fasthttp.Response.Header.SetContentType(utils.GetMIME(extension))
2020-06-06 07:31:33 +02:00
}
2020-09-13 11:20:11 +02:00
return c
2020-02-21 18:07:43 +01:00
}
2020-03-24 05:46:13 +01:00
// Vary adds the given header field to the Vary response header.
2020-03-16 15:29:53 +01:00
// This will append the header, if not already listed, otherwise leaves it listed in the current location.
2020-09-13 11:20:11 +02:00
func (c *Ctx) Vary(fields ...string) {
c.Append(HeaderVary, fields...)
}
2020-09-18 11:52:06 +02:00
// Write appends p into response body.
func (c *Ctx) Write(p []byte) (int, error) {
2020-09-13 11:20:11 +02:00
c.fasthttp.Response.AppendBody(p)
return len(p), nil
2020-02-21 18:07:43 +01:00
}
2020-09-18 11:52:06 +02:00
// WriteString appends s to response body.
func (c *Ctx) WriteString(s string) (int, error) {
c.fasthttp.Response.AppendBodyString(s)
return len(s), nil
}
// XHR returns a Boolean property, that is true, if the request's X-Requested-With header field is XMLHttpRequest,
2020-03-16 15:43:16 +01:00
// indicating that the request was issued by a client library (such as jQuery).
2020-09-13 11:20:11 +02:00
func (c *Ctx) XHR() bool {
2020-09-27 12:22:17 +02:00
return utils.EqualsFold(utils.UnsafeBytes(c.Get(HeaderXRequestedWith)), []byte("xmlhttprequest"))
2020-02-21 18:07:43 +01:00
}
// prettifyPath ...
2020-09-13 11:20:11 +02:00
func (c *Ctx) prettifyPath() {
// If UnescapePath enabled, we decode the path
2020-09-13 11:20:11 +02:00
if c.app.config.UnescapePath {
c.pathBuffer = fasthttp.AppendUnquotedArg(c.pathBuffer[:0], c.pathBuffer)
}
// If CaseSensitive is disabled, we lowercase the original path
2020-09-13 11:20:11 +02:00
if !c.app.config.CaseSensitive {
c.pathBuffer = utils.ToLowerBytes(c.pathBuffer)
}
// If StrictRouting is disabled, we strip all trailing slashes
2020-09-13 11:20:11 +02:00
if !c.app.config.StrictRouting && len(c.pathBuffer) > 1 && c.pathBuffer[len(c.pathBuffer)-1] == '/' {
c.pathBuffer = utils.TrimRightBytes(c.pathBuffer, '/')
}
2020-09-13 11:20:11 +02:00
c.path = getString(c.pathBuffer)
2020-09-13 11:20:11 +02:00
c.treePath = c.treePath[0:0]
if len(c.path) >= 3 {
c.treePath = c.path[:3]
}
}