1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-22 15:03:57 +00:00
fiber/context.go

945 lines
24 KiB
Go
Raw Normal View History

2020-02-22 17:03:30 -05:00
// 🚀 Fiber is an Express inspired web framework written in Go with 💖
// 📌 API Documentation: https://fiber.wiki
// 📝 Github Repository: https://github.com/gofiber/fiber
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"
"fmt"
2020-03-22 20:31:58 +01:00
"html/template"
2020-02-21 18:07:43 +01:00
"io/ioutil"
"log"
"mime"
"mime/multipart"
"net/url"
"path/filepath"
2020-02-29 21:00:54 +08:00
"strconv"
2020-02-21 18:07:43 +01:00
"strings"
"sync"
"time"
jsoniter "github.com/json-iterator/go"
fasthttp "github.com/valyala/fasthttp"
)
// 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.
// For more information please visit our documentation: https://fiber.wiki/context
type Ctx struct {
2020-03-04 12:30:29 +01:00
app *App // Reference to *App
route *Route // Reference to *Route
index int // Index of the current stack
method string // HTTP method
path string // HTTP path
values []string // Route parameter values
Fasthttp *fasthttp.RequestCtx // Reference to *fasthttp.RequestCtx
2020-03-16 15:00:58 +01:00
err error // Contains error if catched
2020-03-04 12:30:29 +01:00
}
// Range struct
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-03-04 12:30:29 +01:00
// Cookie struct
type Cookie struct {
Name string
Value string
Path string
Domain string
Expires time.Time
Secure bool
HTTPOnly bool
2020-03-20 16:43:28 +01:00
SameSite string
2020-03-04 12:30:29 +01:00
}
2020-02-21 18:07:43 +01:00
// Ctx pool
var poolCtx = sync.Pool{
New: func() interface{} {
return new(Ctx)
},
}
// Acquire Ctx from pool
2020-03-03 12:21:34 -05:00
func acquireCtx(fctx *fasthttp.RequestCtx) *Ctx {
2020-02-21 18:07:43 +01:00
ctx := poolCtx.Get().(*Ctx)
2020-03-03 12:21:34 -05:00
ctx.index = -1
2020-03-04 12:30:29 +01:00
ctx.path = getString(fctx.URI().Path())
ctx.method = getString(fctx.Request.Header.Method())
2020-03-03 12:21:34 -05:00
ctx.Fasthttp = fctx
2020-02-21 18:07:43 +01:00
return ctx
}
// Return Ctx to pool
func releaseCtx(ctx *Ctx) {
ctx.route = nil
ctx.values = nil
ctx.Fasthttp = nil
2020-03-04 12:30:29 +01:00
ctx.err = nil
2020-02-21 18:07:43 +01:00
poolCtx.Put(ctx)
}
2020-03-16 15:43:16 +01:00
// Checks, if the specified extensions or content types are acceptable.
//
// https://fiber.wiki/context#accepts
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Accepts(offers ...string) (offer string) {
2020-02-21 18:07:43 +01:00
if len(offers) == 0 {
return ""
}
2020-02-28 06:45:19 +01:00
h := ctx.Get(HeaderAccept)
2020-02-21 18:07:43 +01:00
if h == "" {
return offers[0]
}
specs := strings.Split(h, ",")
2020-02-26 19:31:43 -05:00
for _, value := range offers {
2020-03-20 16:43:28 +01:00
mimetype := getMIME(value)
2020-02-21 18:07:43 +01:00
// if mimetype != "" {
// mimetype = strings.Split(mimetype, ";")[0]
// } else {
// mimetype = offer
// }
for _, spec := range specs {
spec = strings.TrimSpace(spec)
if strings.HasPrefix(spec, "*/*") {
2020-02-26 19:31:43 -05:00
return value
2020-02-21 18:07:43 +01:00
}
if strings.HasPrefix(spec, mimetype) {
2020-02-26 19:31:43 -05:00
return value
2020-02-21 18:07:43 +01:00
}
if strings.Contains(spec, "/*") {
if strings.HasPrefix(spec, strings.Split(mimetype, "/")[0]) {
2020-02-26 19:31:43 -05:00
return value
2020-02-21 18:07:43 +01:00
}
}
}
}
return ""
}
2020-03-16 15:43:16 +01:00
// Checks, if the specified charset is acceptable.
//
// https://fiber.wiki/context#accepts
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) AcceptsCharsets(offers ...string) (offer string) {
2020-02-21 18:07:43 +01:00
if len(offers) == 0 {
return ""
}
2020-02-28 06:45:19 +01:00
h := ctx.Get(HeaderAcceptCharset)
2020-02-21 18:07:43 +01:00
if h == "" {
return offers[0]
}
specs := strings.Split(h, ",")
2020-02-26 19:31:43 -05:00
for _, value := range offers {
2020-02-21 18:07:43 +01:00
for _, spec := range specs {
2020-03-16 17:18:25 +01:00
2020-02-21 18:07:43 +01:00
spec = strings.TrimSpace(spec)
if strings.HasPrefix(spec, "*") {
2020-02-26 19:31:43 -05:00
return value
2020-02-21 18:07:43 +01:00
}
2020-02-26 19:31:43 -05:00
if strings.HasPrefix(spec, value) {
return value
2020-02-21 18:07:43 +01:00
}
}
}
return ""
}
2020-03-16 15:43:16 +01:00
// Checks, if the specified encoding is acceptable.
//
// https://fiber.wiki/context#accepts
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) AcceptsEncodings(offers ...string) (offer string) {
2020-02-21 18:07:43 +01:00
if len(offers) == 0 {
return ""
}
2020-02-28 06:45:19 +01:00
h := ctx.Get(HeaderAcceptEncoding)
2020-02-21 18:07:43 +01:00
if h == "" {
return offers[0]
}
specs := strings.Split(h, ",")
2020-02-26 19:31:43 -05:00
for _, value := range offers {
2020-02-21 18:07:43 +01:00
for _, spec := range specs {
spec = strings.TrimSpace(spec)
if strings.HasPrefix(spec, "*") {
2020-02-26 19:31:43 -05:00
return value
2020-02-21 18:07:43 +01:00
}
2020-02-26 19:31:43 -05:00
if strings.HasPrefix(spec, value) {
return value
2020-02-21 18:07:43 +01:00
}
}
}
return ""
}
2020-03-16 15:43:16 +01:00
// Checks, if the specified language is acceptable.
//
// https://fiber.wiki/context#accepts
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) AcceptsLanguages(offers ...string) (offer string) {
2020-02-21 18:07:43 +01:00
if len(offers) == 0 {
return ""
}
2020-02-28 06:45:19 +01:00
h := ctx.Get(HeaderAcceptLanguage)
2020-02-21 18:07:43 +01:00
if h == "" {
return offers[0]
}
specs := strings.Split(h, ",")
2020-02-26 19:31:43 -05:00
for _, value := range offers {
2020-02-21 18:07:43 +01:00
for _, spec := range specs {
spec = strings.TrimSpace(spec)
if strings.HasPrefix(spec, "*") {
2020-02-26 19:31:43 -05:00
return value
2020-02-21 18:07:43 +01:00
}
2020-02-26 19:31:43 -05:00
if strings.HasPrefix(spec, value) {
return value
2020-02-21 18:07:43 +01:00
}
}
}
return ""
}
2020-03-16 15:43:16 +01:00
// Appends the specified value to the HTTP response header field.
// If the header is not already set, it creates the header with the specified value.
//
// https://fiber.wiki/context#append
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Append(field string, values ...string) {
if len(values) == 0 {
return
}
h := getString(ctx.Fasthttp.Response.Header.Peek(field))
for i := range values {
if h == "" {
h += values[i]
} else {
h += ", " + values[i]
}
}
ctx.Set(field, h)
}
2020-03-16 15:43:16 +01:00
// Sets the HTTP response Content-Disposition header field to attachment.
//
// https://fiber.wiki/context#attachment
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Attachment(name ...string) {
if len(name) > 0 {
filename := filepath.Base(name[0])
ctx.Type(filepath.Ext(filename))
2020-02-28 06:45:19 +01:00
ctx.Set(HeaderContentDisposition, `attachment; filename="`+filename+`"`)
2020-02-21 18:07:43 +01:00
return
}
2020-02-28 06:45:19 +01:00
ctx.Set(HeaderContentDisposition, "attachment")
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Returns base URL (protocol + host) as a string.
//
// https://fiber.wiki/context#baseurl
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) BaseURL() string {
return ctx.Protocol() + "://" + ctx.Hostname()
}
2020-03-16 15:43:16 +01:00
// Contains the raw body submitted in a POST request.
// If a key is provided, it returns the form value
//
// https://fiber.wiki/context#body
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Body(key ...string) string {
// Return request body
if len(key) == 0 {
2020-02-21 18:07:43 +01:00
return getString(ctx.Fasthttp.Request.Body())
}
2020-02-26 19:31:43 -05:00
// Return post value by key
if len(key) > 0 {
return getString(ctx.Fasthttp.Request.PostArgs().Peek(key[0]))
2020-02-21 18:07:43 +01:00
}
return ""
}
2020-03-16 15:43:16 +01:00
// Binds the request body to a struct.
// BodyParser supports decoding the following content types based on the Content-Type header:
// application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data
//
// https://fiber.wiki/context#bodyparser
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) BodyParser(out interface{}) error {
// TODO : Query Params
2020-02-21 18:07:43 +01:00
ctype := getString(ctx.Fasthttp.Request.Header.ContentType())
// application/json
if strings.HasPrefix(ctype, MIMEApplicationJSON) {
2020-02-26 19:31:43 -05:00
return jsoniter.Unmarshal(ctx.Fasthttp.Request.Body(), out)
2020-02-21 18:07:43 +01:00
}
// application/xml text/xml
if strings.HasPrefix(ctype, MIMEApplicationXML) || strings.HasPrefix(ctype, MIMETextXML) {
2020-02-26 19:31:43 -05:00
return xml.Unmarshal(ctx.Fasthttp.Request.Body(), out)
2020-02-21 18:07:43 +01:00
}
// application/x-www-form-urlencoded
if strings.HasPrefix(ctype, MIMEApplicationForm) {
data, err := url.ParseQuery(getString(ctx.Fasthttp.PostBody()))
if err != nil {
return err
}
2020-02-26 19:31:43 -05:00
return schemaDecoder.Decode(out, data)
2020-02-21 18:07:43 +01:00
}
// multipart/form-data
if strings.HasPrefix(ctype, MIMEMultipartForm) {
data, err := ctx.Fasthttp.MultipartForm()
if err != nil {
return err
}
2020-02-26 19:31:43 -05:00
return schemaDecoder.Decode(out, data.Value)
2020-02-21 18:07:43 +01:00
}
2020-02-26 19:31:43 -05:00
return fmt.Errorf("BodyParser: cannot parse content-type: %v", ctype)
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Expire a client cookie (or all cookies if left empty)
//
// https://fiber.wiki/context#clearcookie
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) ClearCookie(key ...string) {
if len(key) > 0 {
for i := range key {
2020-02-21 18:07:43 +01:00
//ctx.Fasthttp.Request.Header.DelAllCookies()
2020-02-26 19:31:43 -05:00
ctx.Fasthttp.Response.Header.DelClientCookie(key[i])
2020-02-21 18:07:43 +01:00
}
return
}
//ctx.Fasthttp.Response.Header.DelAllCookies()
ctx.Fasthttp.Request.Header.VisitAllCookie(func(k, v []byte) {
ctx.Fasthttp.Response.Header.DelClientCookie(getString(k))
})
}
2020-03-16 15:43:16 +01:00
// Set cookie by passing a cookie struct
//
// https://fiber.wiki/context#cookie
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Cookie(cookie *Cookie) {
fcookie := &fasthttp.Cookie{}
fcookie.SetKey(cookie.Name)
fcookie.SetValue(cookie.Value)
fcookie.SetPath(cookie.Path)
fcookie.SetDomain(cookie.Domain)
fcookie.SetExpire(cookie.Expires)
fcookie.SetSecure(cookie.Secure)
2020-03-20 16:43:28 +01:00
if cookie.Secure {
// Secure must be paired with SameSite=None
fcookie.SetSameSite(fasthttp.CookieSameSiteNoneMode)
}
2020-02-26 19:31:43 -05:00
fcookie.SetHTTPOnly(cookie.HTTPOnly)
2020-03-20 16:43:28 +01:00
switch strings.ToLower(cookie.SameSite) {
case "lax":
fcookie.SetSameSite(fasthttp.CookieSameSiteLaxMode)
case "strict":
fcookie.SetSameSite(fasthttp.CookieSameSiteStrictMode)
case "none":
fcookie.SetSameSite(fasthttp.CookieSameSiteNoneMode)
// Secure must be paired with SameSite=None
fcookie.SetSecure(true)
default:
fcookie.SetSameSite(fasthttp.CookieSameSiteDisabled)
}
2020-02-26 19:31:43 -05:00
ctx.Fasthttp.Response.Header.SetCookie(fcookie)
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Get cookie value by key
//
// https://fiber.wiki/context#cookies
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Cookies(key ...string) (value string) {
if len(key) == 0 {
2020-02-28 06:45:19 +01:00
return ctx.Get(HeaderCookie)
2020-02-21 18:07:43 +01:00
}
2020-02-26 19:31:43 -05:00
return getString(ctx.Fasthttp.Request.Header.Cookie(key[0]))
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Transfers the file from path as an attachment.
// 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-02-21 18:07:43 +01:00
// Download : https://fiber.wiki/context#download
func (ctx *Ctx) Download(file string, name ...string) {
filename := filepath.Base(file)
if len(name) > 0 {
filename = name[0]
}
2020-02-28 06:45:19 +01:00
ctx.Set(HeaderContentDisposition, "attachment; filename="+filename)
2020-02-21 18:07:43 +01:00
ctx.SendFile(file)
}
2020-03-16 15:43:16 +01:00
// This contains the error information that thrown by a panic or passed via the Next(err) method.
//
// https://fiber.wiki/context#error
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Error() error {
2020-03-04 12:30:29 +01:00
return ctx.err
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Performs content-negotiation on the Accept HTTP header. It uses Accepts to select a proper format.
// If the header is not specified or there is no proper format, text/plain is used.
//
// https://fiber.wiki/context#format
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Format(body interface{}) {
var b string
2020-02-21 18:07:43 +01:00
accept := ctx.Accepts("html", "json")
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)
}
switch accept {
case "html":
ctx.SendString("<p>" + b + "</p>")
case "json":
if err := ctx.JSON(body); err != nil {
log.Println("Format: error serializing json ", err)
2020-02-21 18:07:43 +01:00
}
2020-02-26 19:31:43 -05:00
default:
ctx.SendString(b)
2020-02-21 18:07:43 +01:00
}
}
2020-03-16 15:43:16 +01:00
// MultipartForm files can be retrieved by name, the first file from the given key is returned.
//
// https://fiber.wiki/context#formfile
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) FormFile(key string) (*multipart.FileHeader, error) {
return ctx.Fasthttp.FormFile(key)
}
2020-03-16 15:43:16 +01:00
// MultipartForm values can be retrieved by name, the first value from the given key is returned.
//
// https://fiber.wiki/context#formvalue
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) FormValue(key string) (value string) {
2020-02-21 18:07:43 +01:00
return getString(ctx.Fasthttp.FormValue(key))
}
2020-03-16 15:43:16 +01:00
// Not implemented yet, pull requests are welcome!
//
// https://fiber.wiki/context#fresh
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Fresh() bool {
return false
}
2020-03-16 15:43:16 +01:00
// Returns the HTTP request header specified by field.
// Field names are case-insensitive
//
// https://fiber.wiki/context#get
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Get(key string) (value string) {
2020-02-21 18:07:43 +01:00
if key == "referrer" {
key = "referer"
}
return getString(ctx.Fasthttp.Request.Header.Peek(key))
}
2020-03-16 15:43:16 +01:00
// Contains the hostname derived from the Host HTTP header.
//
// https://fiber.wiki/context#hostname
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Hostname() string {
return getString(ctx.Fasthttp.URI().Host())
}
2020-03-16 15:43:16 +01:00
// Returns the remote IP address of the request.
//
// https://fiber.wiki/context#Ip
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) IP() string {
return ctx.Fasthttp.RemoteIP().String()
}
2020-03-16 15:43:16 +01:00
// Returns an string slice of IP addresses specified in the X-Forwarded-For request header.
//
// https://fiber.wiki/context#ips
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) IPs() []string {
2020-02-28 06:45:19 +01:00
ips := strings.Split(ctx.Get(HeaderXForwardedFor), ",")
2020-02-21 18:07:43 +01:00
for i := range ips {
ips[i] = strings.TrimSpace(ips[i])
}
return ips
}
2020-03-16 15:43:16 +01:00
// Returns the matching content type,
// if the incoming requests Content-Type HTTP header field matches the MIME type specified by the type parameter.
//
// https://fiber.wiki/context#is
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Is(extension string) (match bool) {
if extension[0] != '.' {
extension = "." + extension
2020-02-21 18:07:43 +01:00
}
2020-02-28 06:45:19 +01:00
exts, _ := mime.ExtensionsByType(ctx.Get(HeaderContentType))
2020-02-21 18:07:43 +01:00
if len(exts) > 0 {
for _, item := range exts {
2020-02-26 19:31:43 -05:00
if item == extension {
2020-02-21 18:07:43 +01:00
return true
}
}
}
2020-02-26 19:31:43 -05:00
return
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Converts any interface or string to JSON using Jsoniter.
// This method also sets the content header to application/json.
//
// https://fiber.wiki/context#json
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) JSON(json interface{}) error {
2020-03-24 03:36:52 +01:00
// raw, err := jsoniter.Marshal(&json)
// if err != nil {
// ctx.Fasthttp.Response.SetBodyString("")
// return err
// }
// ctx.Fasthttp.Response.SetBodyString(getString(raw))
// Set JSON content type
2020-02-21 18:07:43 +01:00
ctx.Fasthttp.Response.Header.SetContentType(MIMEApplicationJSON)
2020-03-24 03:36:52 +01:00
// Get stream from pool
stream := jsonParser.BorrowStream(nil)
// Return stream to pool when done
defer jsonParser.ReturnStream(stream)
// Write struct to stream
stream.WriteVal(&json)
// Check for errors
if stream.Error != nil {
return stream.Error
}
// Set body from stream buffer
ctx.Fasthttp.Response.SetBodyString(getString(stream.Buffer()))
// No errors
2020-02-21 18:07:43 +01:00
return nil
}
2020-03-16 15:43:16 +01:00
// Sends a JSON response with JSONP support.
// This method is identical to JSON, except that it opts-in to JSONP callback support.
// By default, the callback name is simply callback.
//
// https://fiber.wiki/context#jsonp
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) JSONP(json interface{}, callback ...string) error {
raw, err := jsoniter.Marshal(&json)
2020-02-21 18:07:43 +01:00
if err != nil {
return err
}
str := "callback("
2020-02-26 19:31:43 -05:00
if len(callback) > 0 {
str = callback[0] + "("
2020-02-21 18:07:43 +01:00
}
str += getString(raw) + ");"
2020-02-28 06:45:19 +01:00
ctx.Set(HeaderXContentTypeOptions, "nosniff")
2020-02-21 18:07:43 +01:00
ctx.Fasthttp.Response.Header.SetContentType(MIMEApplicationJavaScript)
ctx.Fasthttp.Response.SetBodyString(str)
return nil
}
2020-03-16 15:43:16 +01:00
// Joins the links followed by the property to populate the responses Link HTTP header field.
//
// https://fiber.wiki/context#links
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Links(link ...string) {
h := ""
for i, l := range link {
if i%2 == 0 {
h += "<" + l + ">"
} else {
h += `; rel="` + l + `",`
}
}
if len(link) > 0 {
h = strings.TrimSuffix(h, ",")
2020-02-28 06:45:19 +01:00
ctx.Set(HeaderLink, h)
2020-02-21 18:07:43 +01:00
}
}
2020-03-16 15:43:16 +01:00
// You can pass interface{} values under string keys scoped to the request
// and therefore available to all routes that match the request.
//
// https://fiber.wiki/context#locals
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Locals(key string, value ...interface{}) (val interface{}) {
if len(value) == 0 {
2020-02-21 18:07:43 +01:00
return ctx.Fasthttp.UserValue(key)
}
2020-02-26 19:31:43 -05:00
ctx.Fasthttp.SetUserValue(key, value[0])
return value[0]
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Sets the response Location HTTP header to the specified path parameter.
//
// https://fiber.wiki/context#location
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Location(path string) {
2020-02-28 06:45:19 +01:00
ctx.Set(HeaderLocation, path)
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.
//
// https://fiber.wiki/context#method
2020-03-16 15:00:58 +01:00
func (ctx *Ctx) Method(override ...string) string {
if len(override) > 0 {
ctx.method = override[0]
}
return ctx.method
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Access multipart form entries, you can parse the binary with MultipartForm().
// This returns a map[string][]string, so given a key the value will be a string slice.
//
// https://fiber.wiki/context#multipartform
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) MultipartForm() (*multipart.Form, error) {
return ctx.Fasthttp.MultipartForm()
}
2020-03-16 15:43:16 +01:00
// Next executes the next method in the stack that matches the current route.
// You can pass an optional error for custom error handling.
//
// https://fiber.wiki/context#next
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Next(err ...error) {
ctx.route = nil
ctx.values = nil
if len(err) > 0 {
2020-03-04 12:30:29 +01:00
ctx.err = err[0]
2020-02-21 18:07:43 +01:00
}
2020-03-04 12:30:29 +01:00
ctx.app.nextRoute(ctx)
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Contains the original request URL.
//
// https://fiber.wiki/context#originalurl
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) OriginalURL() string {
return getString(ctx.Fasthttp.Request.Header.RequestURI())
}
2020-03-16 15:43:16 +01:00
// Used to get the route parameters.
// Defaults to empty string "", if the param doesn't exist.
//
// https://fiber.wiki/context#params
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Params(key string) (value string) {
2020-03-04 12:30:29 +01:00
if ctx.route.Params == nil {
2020-02-26 19:31:43 -05:00
return
2020-02-21 18:07:43 +01:00
}
2020-03-04 12:30:29 +01:00
for i := 0; i < len(ctx.route.Params); i++ {
if (ctx.route.Params)[i] == key {
2020-02-21 18:07:43 +01:00
return ctx.values[i]
}
}
2020-02-26 19:31:43 -05:00
return
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:00:58 +01:00
// Returns the path part of the request URL.
// Optionally, you could override the path.
2020-03-16 15:29:53 +01:00
//
2020-03-16 15:00:58 +01:00
// https://fiber.wiki/context#path
func (ctx *Ctx) Path(override ...string) string {
if len(override) > 0 {
// Non strict routing
if !ctx.app.Settings.StrictRouting && len(override[0]) > 1 {
override[0] = strings.TrimRight(override[0], "/")
}
// Not case sensitive
if !ctx.app.Settings.CaseSensitive {
override[0] = strings.ToLower(override[0])
}
2020-03-16 15:00:58 +01:00
ctx.path = override[0]
}
return ctx.path
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:29:53 +01:00
// Contains the request protocol string: http or https for TLS requests.
//
// https://fiber.wiki/context#protocol
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Protocol() string {
if ctx.Fasthttp.IsTLS() {
return "https"
}
return "http"
}
2020-03-16 15:29:53 +01:00
// Returns the query string parameter in the url.
//
// https://fiber.wiki/context#query
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Query(key string) (value string) {
2020-02-21 18:07:43 +01:00
return getString(ctx.Fasthttp.QueryArgs().Peek(key))
}
2020-03-16 15:29:53 +01:00
// An struct containing the type and a slice of ranges will be returned.
//
// https://fiber.wiki/context#range
func (ctx *Ctx) Range(size int) (rangeData Range, err error) {
2020-02-29 21:00:54 +08:00
rangeStr := string(ctx.Fasthttp.Request.Header.Peek("range"))
2020-02-29 21:12:17 +08:00
if rangeStr == "" || !strings.Contains(rangeStr, "=") {
return rangeData, fmt.Errorf("malformed range header string")
2020-02-29 21:00:54 +08:00
}
data := strings.Split(rangeStr, "=")
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 {
return rangeData, fmt.Errorf("malformed range header string")
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 {
return rangeData, fmt.Errorf("unsatisfiable range")
2020-02-29 21:00:54 +08:00
}
return rangeData, nil
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:29:53 +01:00
// Redirects to the URL derived from the specified path, with specified status.
// If status is not specified, status defaults to 302 Found
//
// https://fiber.wiki/context#redirect
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Redirect(path string, status ...int) {
code := 302
if len(status) > 0 {
code = status[0]
}
2020-02-28 06:45:19 +01:00
ctx.Set(HeaderLocation, path)
2020-02-21 18:07:43 +01:00
ctx.Fasthttp.Response.SetStatusCode(code)
}
2020-03-16 15:29:53 +01:00
// Renders a template with data and sends a text/html response.
// We support the following engines: html, amber, handlebars, mustache, pug
//
// https://fiber.wiki/context#render
2020-03-22 21:49:57 +01:00
func (ctx *Ctx) Render(file string, bind interface{}) error {
2020-02-21 18:07:43 +01:00
var err error
var raw []byte
var html string
2020-02-27 05:12:41 -05:00
if ctx.app.Settings.TemplateFolder != "" {
file = filepath.Join(ctx.app.Settings.TemplateFolder, file)
2020-02-21 18:07:43 +01:00
}
2020-02-27 05:12:41 -05:00
if ctx.app.Settings.TemplateExtension != "" {
file = file + ctx.app.Settings.TemplateExtension
2020-02-21 18:07:43 +01:00
}
if raw, err = ioutil.ReadFile(filepath.Clean(file)); err != nil {
return err
}
2020-03-22 20:31:58 +01:00
if ctx.app.Settings.TemplateEngine != nil {
// Custom template engine
// https://github.com/gofiber/template
if html, err = ctx.app.Settings.TemplateEngine(getString(raw), bind); err != nil {
2020-02-21 18:07:43 +01:00
return err
}
2020-03-22 20:31:58 +01:00
} else {
// Default template engine
// https://golang.org/pkg/text/template/
var buf bytes.Buffer
var tmpl *template.Template
if tmpl, err = template.New("").Parse(getString(raw)); err != nil {
2020-02-21 18:07:43 +01:00
return err
}
2020-03-22 20:31:58 +01:00
if err = tmpl.Execute(&buf, bind); err != nil {
2020-02-21 18:07:43 +01:00
return err
}
2020-03-22 20:31:58 +01:00
html = buf.String()
2020-02-21 18:07:43 +01:00
}
ctx.Set("Content-Type", "text/html")
ctx.SendString(html)
return err
}
2020-03-16 15:29:53 +01:00
// Returns the matched Route struct.
//
// https://fiber.wiki/context#route
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Route() *Route {
return ctx.route
}
2020-03-16 15:29:53 +01:00
// Save any multipart file to disk.
//
// https://fiber.wiki/context#secure
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error {
return fasthttp.SaveMultipartFile(fileheader, path)
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:29:53 +01:00
// A boolean property, that is true, if a TLS connection is established.
//
// https://fiber.wiki/context#secure
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Secure() bool {
return ctx.Fasthttp.IsTLS()
}
2020-03-16 15:29:53 +01:00
// Sets the HTTP response body. The Send body can be of any type.
//
// https://fiber.wiki/context#send
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Send(bodies ...interface{}) {
2020-02-26 20:03:59 -05:00
if len(bodies) > 0 {
ctx.Fasthttp.Response.SetBodyString("")
}
2020-02-26 19:31:43 -05:00
for i := range bodies {
switch body := bodies[i].(type) {
case string:
ctx.Fasthttp.Response.AppendBodyString(body)
case []byte:
ctx.Fasthttp.Response.AppendBodyString(getString(body))
default:
ctx.Fasthttp.Response.AppendBodyString(fmt.Sprintf("%v", body))
}
2020-02-21 18:07:43 +01:00
}
}
2020-03-16 15:29:53 +01:00
// Sets the HTTP response body for []byte types
// This means no type assertion, recommended for faster performance
//
// https://fiber.wiki/context#send
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) SendBytes(body []byte) {
ctx.Fasthttp.Response.SetBodyString(getString(body))
}
2020-03-16 15:29:53 +01:00
// Transfers the file from the given path.
// Sets the Content-Type response HTTP header field based on the filenames extension.
//
// https://fiber.wiki/context#sendfile
func (ctx *Ctx) SendFile(file string, compress ...bool) {
2020-02-21 18:07:43 +01:00
// Disable gzipping
2020-03-16 15:29:53 +01:00
if len(compress) > 0 && !compress[0] {
2020-02-21 18:07:43 +01:00
fasthttp.ServeFileUncompressed(ctx.Fasthttp, file)
return
}
fasthttp.ServeFile(ctx.Fasthttp, file)
// https://github.com/valyala/fasthttp/blob/master/fs.go#L81
//ctx.Type(filepath.Ext(path))
//ctx.Fasthttp.SendFile(path)
}
2020-03-16 15:29:53 +01:00
// Sets the HTTP status code and if the response body is empty,
// it sets the correct status message in the body.
//
// https://fiber.wiki/context#sendstatus
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) SendStatus(status int) {
ctx.Fasthttp.Response.SetStatusCode(status)
// Only set status body when there is no response body
if len(ctx.Fasthttp.Response.Body()) == 0 {
2020-03-04 12:30:29 +01:00
ctx.Fasthttp.Response.SetBodyString(statusMessages[status])
2020-02-21 18:07:43 +01:00
}
}
2020-03-16 15:29:53 +01:00
// Sets the HTTP response body for string types
// This means no type assertion, recommended for faster performance
//
// https://fiber.wiki/context#send
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) SendString(body string) {
ctx.Fasthttp.Response.SetBodyString(body)
}
2020-03-16 15:29:53 +01:00
// Sets the responses HTTP header field to the specified key, value.
//
// https://fiber.wiki/context#set
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Set(key string, val string) {
2020-03-14 12:30:21 +01:00
ctx.Fasthttp.Response.Header.Set(key, val)
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:29:53 +01:00
// Returns a string slive of subdomains in the domain name of the request.
// The subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.
//
// https://fiber.wiki/context#subdomains
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Subdomains(offset ...int) []string {
2020-02-21 18:07:43 +01:00
o := 2
if len(offset) > 0 {
o = offset[0]
}
2020-02-26 19:31:43 -05:00
subdomains := strings.Split(ctx.Hostname(), ".")
subdomains = subdomains[:len(subdomains)-o]
return subdomains
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:29:53 +01:00
// Not implemented yet, pull requests are welcome!
//
// https://fiber.wiki/context#stale
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Stale() bool {
return !ctx.Fresh()
}
2020-03-16 15:29:53 +01:00
// Sets the HTTP status for the response.
// This method is chainable.
//
// https://fiber.wiki/context#status
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Status(status int) *Ctx {
ctx.Fasthttp.Response.SetStatusCode(status)
return ctx
}
2020-03-16 15:29:53 +01:00
// Sets the Content-Type HTTP header to the MIME type specified by the file extension.
//
// https://fiber.wiki/context#type
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Type(ext string) *Ctx {
2020-03-20 16:43:28 +01:00
ctx.Fasthttp.Response.Header.SetContentType(getMIME(ext))
2020-02-21 18:07:43 +01:00
return ctx
}
2020-03-16 15:29:53 +01:00
// Adds the given header field to the Vary response header.
// This will append the header, if not already listed, otherwise leaves it listed in the current location.
//
// https://fiber.wiki/context#vary
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) Vary(fields ...string) {
if len(fields) == 0 {
return
}
2020-02-28 06:45:19 +01:00
h := getString(ctx.Fasthttp.Response.Header.Peek(HeaderVary))
2020-02-21 18:07:43 +01:00
for i := range fields {
if h == "" {
h += fields[i]
} else {
h += ", " + fields[i]
}
}
2020-02-28 06:45:19 +01:00
ctx.Set(HeaderVary, h)
2020-02-21 18:07:43 +01:00
}
2020-03-16 15:43:16 +01:00
// Appends any input to the HTTP body response.
//
// https://fiber.wiki/context#write
2020-02-26 19:31:43 -05:00
func (ctx *Ctx) Write(bodies ...interface{}) {
for i := range bodies {
switch body := bodies[i].(type) {
2020-02-21 18:07:43 +01:00
case string:
ctx.Fasthttp.Response.AppendBodyString(body)
case []byte:
ctx.Fasthttp.Response.AppendBodyString(getString(body))
default:
ctx.Fasthttp.Response.AppendBodyString(fmt.Sprintf("%v", body))
}
}
}
2020-03-16 15:43:16 +01:00
// A Boolean property, that is true, if the requests X-Requested-With header field is XMLHttpRequest,
// indicating that the request was issued by a client library (such as jQuery).
//
// https://fiber.wiki/context#xhr
2020-02-21 18:07:43 +01:00
func (ctx *Ctx) XHR() bool {
2020-02-28 06:45:19 +01:00
return ctx.Get(HeaderXRequestedWith) == "XMLHttpRequest"
2020-02-21 18:07:43 +01:00
}