diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000000..f53dc3b9c25 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,8 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +custom: # Replace with a single custom sponsorship URL diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000000..8a8e29a827d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,40 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[🐞] " +labels: "" +assignees: "" +--- + +☝️ **Don't forget to add title above!** ☝️ + +**Your environment:** + +- Fiber Web Framework [e.g. `1.2.3`]: +- OS [e.g. `macOS 10.14.6`]: +- Golang [e.g. `1.13.7`]: + +## Describe the bug + +A clear and concise description of what the bug is. + +## To reproduce + +Steps to reproduce the behavior: + +1. Create func '...' +2. Run '...' +3. ... +4. See error + +## Expected behavior + +A clear and concise description of what you expected to happen. + +### Screenshots + +If applicable, add screenshots to help explain your problem. + +### Additional context + +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000000..a45c085ced0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,21 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[🔥] " +labels: "" +assignees: "" +--- + +☝️ **Don't forget to add title above!** ☝️ + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/config.yml b/.github/config.yml new file mode 100644 index 00000000000..ef12862e8cc --- /dev/null +++ b/.github/config.yml @@ -0,0 +1,14 @@ +# Configuration for new-issue-welcome - https://github.com/behaviorbot/new-issue-welcome +# Comment to be posted to on first time issues +newIssueWelcomeComment: > + Thanks for opening your first issue here! 🎉 Be sure to follow the issue template! + +# Configuration for new-pr-welcome - https://github.com/behaviorbot/new-pr-welcome +# Comment to be posted to on PRs from first time contributors in your repository +newPRWelcomeComment: > + Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. + +# Configuration for first-pr-merge - https://github.com/behaviorbot/first-pr-merge +# Comment to be posted to on pull requests merged by a first time user +firstPRMergeComment: > + Congrats on merging your first pull request! 🎉 We here at behaviorbot are proud of you! \ No newline at end of file diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 00000000000..3c82d70d5db --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,26 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 60 + +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 + +# Issues with these labels will never be considered stale +exemptLabels: + - pinned + - security + +# Label to use when marking an issue as stale +staleLabel: wontfix + +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + 👋 Hello. Is this still relevant? If so, what is blocking it? Is there + anything you can do to help move it forward? + + > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. + + Thank you for your contributions. + +# Comment to post when closing a stale Issue or Pull Request. Set to `false` to disable +closeComment: > + ⚡️ This issue has been automatically closed because it has not had recent activity. \ No newline at end of file diff --git a/README.md b/README.md index f6e1085b9d7..0e093477a85 100644 --- a/README.md +++ b/README.md @@ -1,113 +1,155 @@ -
-
-
+
+**[Fiber](https://github.com/gofiber/fiber)** is an [Express](https://expressjs.com/en/4x/api.html)-styled HTTP web framework implementation running on [Fasthttp](https://github.com/valyala/fasthttp), the **fastest** HTTP engine for Go (Golang). The package make use of **similar framework convention** as they are in Express.
+
+People switching from [Node.js](https://nodejs.org/en/about/) to [Go](https://golang.org/doc/) often end up in a bad learning curve to start building their webapps, this project is meant to **ease** things up for **fast** development, but with **zero memory allocation** and **performance** in mind.
+
+**In other languages:**
+
+**[Fiber](https://github.com/gofiber/fiber)** — это [Express](https://expressjs.com/en/4x/api.html)-подобный HTTP веб фреймворк, использующий всю мощь [Fasthttp](https://github.com/valyala/fasthttp), самого **быстрого** HTTP движка для Go (Golang). Мы используем **аналогичную** схему именования методов, как и у Express.
+
+Разработчики, пришедшие из [Node.js](https://nodejs.org/en/about/) в [Go](https://golang.org/doc/) очень часто испытывают трудности при создании своих первых веб-приложений. Данный проект призван, в том числе, **облегчить** процесс перехода для таких разработчиков.
+
+**На других языках:**
-
+
You can enable the **prefork** feature by adding the **-prefork** flag.
@@ -83,6 +92,7 @@ You can enable the **prefork** feature by adding the **-prefork** flag.
```
Or enable the **Prefork** option in your app.
+
```go
app := fiber.New()
@@ -99,7 +109,9 @@ app.Listen(8080)
```
#### Methods
+
Routes an HTTP request, where METHOD is the [HTTP method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) of the request, such as GET, PUT, POST, and so on capitalized. Thus, the actual methods are **app.Get()**, **app.Post()**, **app.Put()**, and so on.
+
```go
// Function signature
app.Get(handler func(*Ctx))
@@ -123,36 +135,47 @@ app.Use(...) // Will only see wheter url starts with specified path without :par
```
#### Static
+
To serve static files such as images, CSS files, and JavaScript files, replace your function handler with a file or directory string.
By default this method will send `index.html` files in response to a request on a directory.
+
```go
// Function signature
app.Static(root string)
app.Static(prefix, root string)
```
+
For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:
```go
app.Static("./public")
```
+
Now, you can load the files that are in the public directory:
+
```shell
http://localhost:8080/hello.html
http://localhost:8080/js/jquery.js
http://localhost:8080/css/style.css
```
+
To use multiple static assets directories, call the Static function multiple times:
+
```go
app.Static("./public")
app.Static("./files")
```
-?>For best results, use a reverse proxy cache like [NGINX](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/) to improve performance of serving static assets.
+
+?>For best results, use a reverse proxy cache like [NGINX](https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/) to improve performance of serving static assets.
To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:
+
```go
app.Static("/static", "./public")
```
+
Now, you can load the files that are in the public directory from the /static path prefix.
+
```shell
http://localhost:8080/static/hello.html
http://localhost:8080/static/js/jquery.js
@@ -160,7 +183,9 @@ http://localhost:8080/static/css/style.css
```
#### Listen
+
Binds and listens for connections on the specified address. This can be a **INT** for port or **STRING** for address. To enable **TLS/HTTPS** you can append your **cert** and **key** path.
+
```go
// Function signature
app.Listen(address interface{}, tls ...string)
@@ -175,5 +200,4 @@ app.Listen("127.0.0.1:8080")
app.Listen(443, "server.crt", "server.key")
```
-
-*Caught a mistake? [Edit this page on GitHub!](https://github.com/gofiber/fiber/blob/master/docs/application.md)*
+_Caught a mistake? [Edit this page on GitHub!](https://github.com/gofiber/fiber/blob/master/docs/application.md)_
diff --git a/docs/benchmarks.md b/docs/benchmarks.md
index b0b151fa4ab..b81f2ca291c 100644
--- a/docs/benchmarks.md
+++ b/docs/benchmarks.md
@@ -1,16 +1,16 @@
# Benchmarks
#### TechEmpower
-* **CPU** Intel Xeon Gold 5120
-* **MEM** 32GB
-* **GO** go1.13.6 linux/amd64
-* **OS** Linux
-* **NET** Dedicated Cisco 10-gigabit Ethernet switch.
+- **CPU** Intel Xeon Gold 5120
+- **MEM** 32GB
+- **GO** go1.13.6 linux/amd64
+- **OS** Linux
+- **NET** Dedicated Cisco 10-gigabit Ethernet switch.
Below you can see the results of tested go frameworks responding in plaintext.
To view the list yourself, [Plaintext Go Results](https://www.techempower.com/benchmarks/#section=test&runid=350f0783-cc9b-4259-9831-28987799782a&hw=ph&test=plaintext&l=zijocf-1r).
-To see all language frameworks, [Plaintext All Results](https://www.techempower.com/benchmarks/#section=test&runid=350f0783-cc9b-4259-9831-28987799782a&hw=ph&test=plaintext).
+To see all language frameworks, [Plaintext All Results](https://www.techempower.com/benchmarks/#section=test&runid=350f0783-cc9b-4259-9831-28987799782a&hw=ph&test=plaintext).
Plaintext
[](https://www.techempower.com/benchmarks/#section=test&runid=350f0783-cc9b-4259-9831-28987799782a&hw=ph&test=plaintext&l=zijocf-1r)
@@ -31,14 +31,15 @@ Data updates
[](https://www.techempower.com/benchmarks/#section=test&runid=350f0783-cc9b-4259-9831-28987799782a&hw=ph&test=update&l=zijocf-1r)
#### Go-Web
+
[go-web-framework-benchmark](https://github.com/smallnest/go-web-framework-benchmark)
-* **CPU** Intel(R) Xeon(R) Gold 6140 CPU @ 2.30GHz
-* **MEM** 4GB
-* **GO** go1.13.6 linux/amd64
-* **OS** Linux
+- **CPU** Intel(R) Xeon(R) Gold 6140 CPU @ 2.30GHz
+- **MEM** 4GB
+- **GO** go1.13.6 linux/amd64
+- **OS** Linux
-The first test case is to mock 0 ms, 10 ms, 100 ms, 500 ms processing time in handlers.
+The first test case is to mock 0 ms, 10 ms, 100 ms, 500 ms processing time in handlers.

@@ -68,8 +69,8 @@ If we enable http pipelining, test result as below:

-
-*Caught a mistake? [Edit this page on GitHub!](https://github.com/Fenny/fiber/blob/master/docs/benchmarks.md)*
+_Caught a mistake? [Edit this page on GitHub!](https://github.com/Fenny/fiber/blob/master/docs/benchmarks.md)_
diff --git a/docs/context.md b/docs/context.md
index beb2c1951a7..33b8faa97b5 100644
--- a/docs/context.md
+++ b/docs/context.md
@@ -1,8 +1,11 @@
# Context
+
The ctx object represents the HTTP request and response and has methods for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the context is always referred to as c but its actual name is determined by the parameters to the callback function in which you’re working.
#### Accepts
+
Checks if the specified content types are acceptable, based on the request’s Accept HTTP header field. You can use an extention or content-type format
+
```go
// Function signature
c.Accepts(types ...string) string
@@ -31,7 +34,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### AcceptsCharsets
+
Returns the first accepted charset of the specified character sets, based on the request’s Accept-Charset HTTP header field
+
```go
// Function signature
c.AcceptsCharsets(charsets ...string) string
@@ -50,9 +55,10 @@ app.Get("/", func(c *fiber.Ctx) {
})
```
-
#### AcceptsEncodings
+
Returns the first accepted encoding of the specified encodings, based on the request’s Accept-Encoding HTTP header field.
+
```go
// Function signature
c.AcceptsEncodings(encodings ...string) string
@@ -72,7 +78,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### AcceptsLanguages
+
Returns the first accepted language of the specified languages, based on the request’s Accept-Language HTTP header field.
+
```go
// Function signature
c.AcceptsLanguages(languages ...string) string
@@ -92,7 +100,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Append
+
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. The value parameter must be a string.
+
```go
// Function signature
c.Append(field, values ...string)
@@ -113,7 +123,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Attachment
-Sets the HTTP response [Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header field to “attachment”. If a filename is given, then it sets the Content-Type based on the extension name via (Type)[#type], and sets the Content-Disposition “filename=” parameter.
+
+Sets the HTTP response [Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header field to “attachment”. If a filename is given, then it sets the Content-Type based on the extension name via [Type](#type), and sets the Content-Disposition “filename=” parameter.
+
```go
// Function signature
c.Attachment(file ...string)
@@ -129,24 +141,28 @@ app.Get("/", func(c *fiber.Ctx) {
})
```
-#### BaseUrl
+#### BaseURL
#### AcceptsLanguages
+
Returns the base URL, protocol and hostname combined.
+
```go
// Function signature
-c.BaseUrl() bool
+c.BaseURL() bool
// Example
app.Get("/", func(c *fiber.Ctx) {
// http://webtech.oregonstate.edu/faq/page/2?sort=date
- c.BaseUrl()
+ c.BaseURL()
// => "http://webtech.oregonstate.edu"
})
```
#### BasicAuth
+
BasicAuth returns the username and password provided in the request's Authorization header, if the request uses [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
+
```go
// Function signature
c.BasicAuth() (user, pass string, ok bool)
@@ -167,10 +183,12 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Body
+
Contains the raw post body submitted in the request.
Calling a key in body returns a string value if exist or you loop trough the body params using a key value function callback.
The following example shows how to use the body function.
+
```go
// Function signature
c.Body() string
@@ -190,14 +208,16 @@ app.Post("/", func(c *fiber.Ctx) {
// Loop trough all body params
c.Body(func(key string, val string) {
- fmt.Printl(key, val)
+ fmt.Printl(key, val)
// => "user" "john"
})
})
```
#### ClearCookie
+
Clears all client cookies or a specific cookie by name by setting the expire date in the past.
+
```go
// Function signature
c.ClearCookie()
@@ -217,7 +237,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Cookie
+
Sets cookie name to value, the third options parameter is not implemented yet.
+
```go
// Function signature
c.Cookie(name, value string)
@@ -259,7 +281,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Cookies
+
Get cookies
+
```go
// Function signature
c.Cookies() string
@@ -287,7 +311,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Download
+
Transfers the file at path as an “attachment”. Typically, browsers will prompt the user for download. By default, the Content-Disposition header “filename=” parameter is path (this typically appears in the browser dialog). Override this default with the filename parameter.
+
```go
// Function signature
c.Download(path string)
@@ -304,11 +330,14 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### !End
+
!> Planned for v2.0.0
#### Fasthttp
+
You can still access and use all Fasthttp methods and properties.
Please read the [Fasthttp Documentation](https://godoc.org/github.com/valyala/fasthttp) for more information
+
```go
// Function signature
c.Fasthttp...
@@ -324,6 +353,7 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Format
+
Performs content-negotiation on the Accept HTTP header. It uses [Accepts](#accepts) to select a proper format. If the header is not specified or there is no proper format, text/plain is used.
```go
@@ -348,7 +378,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### FormFile
+
MultipartForm files can be retrieved by name, the first file from the given key is returned.
+
```go
// Function signature
c.FormFile(name string) (*multipart.FileHeader, error)
@@ -367,7 +399,9 @@ app.Post("/", func(c *fiber.Ctx) {
```
#### FormValue
+
MultipartForm values can be retrieved by name, the first value from the given key is returned.
+
```go
// Function signature
c.FormValue(name string) string
@@ -381,10 +415,13 @@ app.Post("/", func(c *fiber.Ctx) {
```
#### !Fresh
+
!> Planned for v2.0.0
#### Get
+
Returns the HTTP response header specified by field. The match is case-insensitive.
+
```go
// Function signature
c.Get(field string) string
@@ -403,10 +440,13 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### !HeadersSent
+
!> Planned for v2.0.0
#### Hostname
+
Contains the hostname derived from the Host HTTP header.
+
```go
// Function signature
c.Hostname() string
@@ -420,7 +460,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Ip
+
Contains the remote IP address of the request.
+
```go
// Function signature
c.Ip() string
@@ -433,7 +475,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Ips
+
contains an array of IP addresses specified in the X-Forwarded-For request header.
+
```go
// Function signature
c.Ips() []string
@@ -447,7 +491,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### 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. If the request has no body, returns false.
+
```go
// Function signature
c.Is(typ string) bool
@@ -455,22 +501,24 @@ c.Is(typ string) bool
// Example
app.Get("/", func(c *fiber.Ctx) {
// Content-Type: text/html; charset=utf-8
- c.Is("html")
+ c.Is("html")
// => true
c.Is(".html")
// => true
- c.Is("json")
+ c.Is("json")
// => false
})
```
-#### Json
+#### JSON
+
Converts any interface or string to json using [Jsoniter](https://github.com/json-iterator/go), this function also sets the content header to application/json.
+
```go
// Function signature
-c.Json(v interface{}) error
+c.JSON(v interface{}) error
// Example
type SomeStruct struct {
@@ -484,90 +532,98 @@ app.Get("/json", func(c *fiber.Ctx) {
Name: "Grame",
Age: 20,
}
- c.Json(data)
+ c.JSON(data)
// => "{"Name": "Grame", "Age": 20}"
- c.Json("Hello, World!")
+ c.JSON("Hello, World!")
// => "Hello, World!"
})
app.Listen(8080)
```
Or with error checking
+
```go
app.Get("/json", func(c *fiber.Ctx) {
data := SomeStruct{
Name: "Grame",
Age: 20,
}
- if err := c.Json(data); err != nil {
+ if err := c.JSON(data); err != nil {
c.Status(500).Send("Bad Request")
}
// => "{"Name": "Grame", "Age": 20}"
})
```
-#### JsonBytes
+#### JSONBytes
+
This function accepts raw []byte bodies and sets the content header to application/json. This function is used if you do not need type assertion.
+
```go
// Function signature
-c.Json(json []byte)
+c.JSON(json []byte)
// Example
app := fiber.New()
app.Get("/json", func(c *fiber.Ctx) {
- c.JsonBytes([]byte(`"{"hello": "world"}"`))
+ c.JSONBytes([]byte(`"{"hello": "world"}"`))
})
app.Listen(8080)
```
+#### JSONP
-#### Jsonp
-Sends a JSON response with JSONP support. This method is identical to [Json()](#json), except that it opts-in to JSONP callback support.
+Sends a JSON response with JSONP support. This method is identical to [JSON()](#json), except that it opts-in to JSONP callback support.
By default, the JSONP callback name is simply callback. Override this by passing a named string in the function.
+
```go
// Function signature
-c.Jsonp(v interface{}) error
-c.Jsonp(v interface{}, callback string) error
+c.JSONP(v interface{}) error
+c.JSONP(v interface{}, callback string) error
// Example
-type JsonStruct struct {
+type SomeStruct struct {
name string
age uint8
}
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) {
- data := JsonStruct{
+ data := SomeStruct{
name: "Grame",
age: 20,
}
- c.Jsonp(data)
+ c.JSONP(data)
// => callback({"name": "Grame", "age": 20})
- c.Jsonp(data, "customFunc")
+ c.JSONP(data, "customFunc")
// => customFunc({"name": "Grame", "age": 20})
})
app.Listen(8080)
```
-#### JsonString
+#### JSONString
+
This function accepts raw string body and sets the content header to application/json. This function is used if you do not need type assertion.
+
```go
// Function signature
-c.Json(json string)
+c.JSON(json string)
// Example
app := fiber.New()
app.Get("/json", func(c *fiber.Ctx) {
- c.JsonString(`"{"hello": "world"}"`)
+ c.JSONString(`"{"hello": "world"}"`)
})
app.Listen(8080)
```
#### Links
+
Joins the links followed by the propery to populate the response’s Link HTTP header field.
+
```go
// Function signature
c.Links(link ...string)
@@ -584,9 +640,11 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Locals
-A function that stores string variables scoped to the request, and therefore available only to the routes that match the request.
+
+A function that stores string variables scoped to the request, and therefore available only to the routes that match the request.
This is usefull if you want to pass some specific values to the next middleware.
+
```go
// Function signature
c.Locals(key string)
@@ -608,6 +666,7 @@ app.Get("/", func(c *fiber.Ctx) {
```
You can put any type inside the locals, don't forget to convert it back when you are using the variable
+
```go
type JSON struct {
Message string `json:"message"`
@@ -627,7 +686,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Location
+
Sets the response Location HTTP header to the specified path parameter.
+
```go
// Function signature
c.Location(path string)
@@ -640,7 +701,9 @@ app.Post("/", func(c *fiber.Ctx) {
```
#### Method
+
Contains a string corresponding to the HTTP method of the request: GET, POST, PUT, and so on.
+
```go
// Function signature
c.Method() string
@@ -653,9 +716,11 @@ app.Post("/", func(c *fiber.Ctx) {
```
#### MultipartForm
+
To 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.
So accepting multiple files or values is easy, as shown below!
+
```go
// Function signature
c.MultipartForm() (*multipart.Form, error)
@@ -688,7 +753,9 @@ app.Post("/", func(c *fiber.Ctx) {
```
#### Next
+
When Next() is called, it executes the next function in the stack that matches the current route.
+
```go
// Function signature
c.Next()
@@ -708,22 +775,26 @@ app.Get("/", func(c *fiber.Ctx) {
})
```
-#### OriginalUrl
+#### OriginalURL
+
Contains the original request URL.
+
```go
// Function signature
-c.OriginalUrl() string
+c.OriginalURL() string
// Example
app.Get("/", func(c *fiber.Ctx) {
// GET /search?q=something
- c.OriginalUrl()
+ c.OriginalURL()
// => '/search?q=something'
})
```
#### Params
+
This method can be used to get the route parameters. For example, if you have the route /user/:name, then the “name” property is available as c.Params("name"). This method defaults "".
+
```go
// Function signature
c.Params(param string) string
@@ -737,7 +808,9 @@ app.Get("/user/:name", func(c *fiber.Ctx) {
```
#### Path
+
Contains the path part of the request URL.
+
```go
// Function signature
c.Path() string
@@ -751,6 +824,7 @@ app.Get("/users", func(c *fiber.Ctx) {
```
#### Protocol
+
Contains the request protocol string: either http or (for TLS requests) https.
```go
@@ -763,8 +837,11 @@ app.Get("/", func(c *fiber.Ctx) {
// => "http"
})
```
+
#### Query
+
This property is an object containing a property for each query string parameter in the route. If there is no query string, it returns an empty string
+
```go
// Function signature
c.Query(parameter string) string
@@ -782,10 +859,13 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### !Range
+
!> Planned for v2.0.0
#### Redirect
+
Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to “302 “Found”.
+
```go
// Function signature
c.Redirect(path string)
@@ -801,11 +881,14 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### !Render
+
!> Planned for v2.0.0
#### Route
+
Contains the currently-matched route struct, **only use this for debugging**.
It returns an anonymous struct as shown below.
+
```go
// Function signature
c.Route() struct {
@@ -830,8 +913,8 @@ app.Post("/:api?", func(c *fiber.Ctx) {
})
```
-
#### SaveFile
+
This function is used to save any multipart file to disk.
You can see a working example here: [Multiple file upload](#multipartform)
@@ -841,6 +924,7 @@ c.SaveFile(fh *multipart.FileHeader, path string)
```
#### Secure
+
A Boolean property that is true if a TLS connection is established.
```go
@@ -852,9 +936,11 @@ c.Protocol() == "https"
```
#### Send
+
Sends the HTTP response.
The Send parameters can be of any type
+
```go
// Function signature
c.Send(body ...interface{})
@@ -873,8 +959,10 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### SendBytes
+
Same as Send() but without type assertion.
I suggest using this in production for optimal performance.
+
```go
// Function signature
c.SendBytes(body []byte)
@@ -886,7 +974,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### SendFile
-Transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension.
+
+Transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension.
+
```go
// Function signature
c.SendFile(path string)
@@ -902,7 +992,9 @@ app.Get("/not-found", func(c *fiber.Ctx) {
```
#### SendStatus
+
Sets the status code, but also the correct status message in the body if the response body is still empty. You can find all status codes and messages in [status.go](https://github.com/gofiber/fiber/blob/master/status.go)
+
```go
// Function signature
c.SendStatus(status int)
@@ -921,8 +1013,10 @@ app.Get("/not-found", func(c *fiber.Ctx) {
```
#### SendString
+
Same as Send() but without type assertion.
I suggest using this in production for optimal performance.
+
```go
// Function signature
c.SendString(body string)
@@ -934,7 +1028,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Set
+
Sets the response’s HTTP header field to value. To set multiple fields at once, pass an object as the parameter.
+
```go
// Function signature
c.Set(key, value string)
@@ -947,13 +1043,17 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### !SignedCookies
+
!> Planned for v2.0.0
#### !Stale
+
!> Planned for v2.0.0
#### Status
+
Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.
+
```go
// Function signature
c.Status(status int)
@@ -967,8 +1067,10 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Subdomains
+
An array of subdomains in the domain name of the request.
The application property subdomain offset, which defaults to 2, is used for determining the beginning of the subdomain segments.
+
```go
// Function signature
c.Subdomains() []string
@@ -982,7 +1084,9 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Type
+
Sets the Content-Type HTTP header to the MIME type listed [here](https://github.com/nginx/nginx/blob/master/conf/mime.types) specified by the file extension.
+
```go
// Function signature
c.Type(typ string) string
@@ -1004,9 +1108,11 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Vary
+
Adds the given header field to the Vary response header of res. This can be a single field, or multiple fields.
This will append the header if not already listed, otherwise leaves it listed in the current location.
+
```go
// Function signature
c.Vary(field ...string)
@@ -1033,9 +1139,11 @@ app.Get("/", func(c *fiber.Ctx) {
```
#### Write
+
Appends to the HTTP response.
The Write parameter can be any type
+
```go
// Function signature
c.Write(bodies ...interface{})
@@ -1056,24 +1164,28 @@ app.Get("/", func(c *fiber.Ctx) {
})
```
-#### Xhr
+#### XHR
+
A Boolean property that is true if the request’s **X-Requested-With** header field is **XMLHttpRequest**, indicating that the request was issued by a client library such as [jQuery](https://api.jquery.com/jQuery.ajax/).
+
```go
// Function signature
-c.Xhr() bool
+c.XHR() bool
// Example
app.Get("/", func(c *fiber.Ctx) {
- c.Xhr()
+ c.XHR()
// => true
})
```
-#### Xml
-Xml sets the header to "application/xml" and marshals your interface to xml.
+#### XML
+
+XML sets the header to "application/xml" and marshals your interface to xml.
+
```go
// Function signature
-c.Xml(xml interface{}) error
+c.XML(xml interface{}) error
// Example
type person struct {
@@ -1083,7 +1195,7 @@ type person struct {
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) {
- c.Xml(person{"John", 50})
+ c.XML(person{"John", 50})
// => Content-Type: application/xml
// => 
" + body + "
") case "json": - ctx.Json(body) + if err := ctx.JSON(body); err != nil { + log.Fatal(err) + } default: ctx.SendString(body) } @@ -143,29 +156,32 @@ func (ctx *Ctx) HeadersSent() { } -// Json : https://gofiber.github.io/fiber/#/context?id=json -func (ctx *Ctx) Json(v interface{}) error { +// JSON : https://gofiber.github.io/fiber/#/context?id=json +func (ctx *Ctx) JSON(v interface{}) error { raw, err := jsoniter.Marshal(&v) if err != nil { return err } - ctx.Fasthttp.Response.Header.SetContentType(contentTypeJson) + + ctx.Fasthttp.Response.Header.SetContentType(contentTypeJSON) ctx.Fasthttp.Response.SetBodyString(getString(raw)) + return nil } -// JsonBytes : https://gofiber.github.io/fiber/#/context?id=jsonbytes -func (ctx *Ctx) JsonBytes(raw []byte) { - ctx.Fasthttp.Response.Header.SetContentType(contentTypeJson) +// JSONBytes : https://gofiber.github.io/fiber/#/context?id=jsonbytes +func (ctx *Ctx) JSONBytes(raw []byte) { + ctx.Fasthttp.Response.Header.SetContentType(contentTypeJSON) ctx.Fasthttp.Response.SetBodyString(getString(raw)) } -// Jsonp : https://gofiber.github.io/fiber/#/context?id=jsonp -func (ctx *Ctx) Jsonp(v interface{}, cb ...string) error { +// JSONP : https://gofiber.github.io/fiber/#/context?id=jsonp +func (ctx *Ctx) JSONP(v interface{}, cb ...string) error { raw, err := jsoniter.Marshal(&v) if err != nil { return err } + str := "callback(" if len(cb) > 0 { str = cb[0] + "(" @@ -175,12 +191,13 @@ func (ctx *Ctx) Jsonp(v interface{}, cb ...string) error { ctx.Set(fasthttp.HeaderXContentTypeOptions, "nosniff") ctx.Fasthttp.Response.Header.SetContentType(contentTypeJs) ctx.Fasthttp.Response.SetBodyString(str) + return nil } -// JsonString : https://gofiber.github.io/fiber/#/context?id=jsonstring -func (ctx *Ctx) JsonString(raw string) { - ctx.Fasthttp.Response.Header.SetContentType(contentTypeJson) +// JSONString : https://gofiber.github.io/fiber/#/context?id=jsonstring +func (ctx *Ctx) JSONString(raw string) { + ctx.Fasthttp.Response.Header.SetContentType(contentTypeJSON) ctx.Fasthttp.Response.SetBodyString(raw) } @@ -194,6 +211,7 @@ func (ctx *Ctx) Links(link ...string) { h += `; rel="` + l + `",` } } + if len(link) > 0 { h = strings.TrimSuffix(h, ",") ctx.Set(fasthttp.HeaderLink, h) @@ -219,6 +237,7 @@ func (ctx *Ctx) Redirect(path string, status ...int) { if len(status) > 0 { code = status[0] } + ctx.Set(fasthttp.HeaderLocation, path) ctx.Fasthttp.Response.SetStatusCode(code) } @@ -233,6 +252,7 @@ func (ctx *Ctx) Send(args ...interface{}) { if len(args) == 0 { return } + switch body := args[0].(type) { case string: ctx.Fasthttp.Response.SetBodyString(body) @@ -255,6 +275,7 @@ func (ctx *Ctx) SendFile(file string, gzip ...bool) { 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)) @@ -264,6 +285,7 @@ func (ctx *Ctx) SendFile(file string, gzip ...bool) { // SendStatus : https://gofiber.github.io/fiber/#/context?id=sendstatus 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 { msg := getStatus(status) @@ -300,12 +322,14 @@ func (ctx *Ctx) Vary(fields ...string) { if len(fields) == 0 { return } + vary := ctx.Get(fasthttp.HeaderVary) for _, field := range fields { if !strings.Contains(vary, field) { vary += ", " + field } } + ctx.Set(fasthttp.HeaderVary, vary) } @@ -323,13 +347,15 @@ func (ctx *Ctx) Write(args ...interface{}) { } } -// Xml : https://gofiber.github.io/fiber/#/context?id=xml -func (ctx *Ctx) Xml(v interface{}) error { +// XML : https://gofiber.github.io/fiber/#/context?id=xml +func (ctx *Ctx) XML(v interface{}) error { raw, err := xml.Marshal(v) if err != nil { return err } - ctx.Fasthttp.Response.Header.SetContentType(contentTypeXml) + + ctx.Fasthttp.Response.Header.SetContentType(contentTypeXML) ctx.Fasthttp.Response.SetBody(raw) + return nil } diff --git a/router.go b/router.go index 2ff25d21a59..01377d2482e 100644 --- a/router.go +++ b/router.go @@ -1,4 +1,4 @@ -// 🔌 Fiber is an Expressjs inspired web framework build on 🚀 Fasthttp. +// 🔌 Fiber is an Express.js inspired web framework build on 🚀 Fasthttp. // 📌 Please open an issue if you got suggestions or found a bug! // 🖥 https://github.com/gofiber/fiber @@ -14,10 +14,11 @@ import ( "github.com/valyala/fasthttp" ) -type route struct { +// Route : struct +type Route struct { // HTTP method in uppercase, can be a * for Use() & All() Method string - // Stores the orignal path + // Stores the original path Path string // Bool that defines if the route is a Use() middleware Midware bool @@ -35,13 +36,16 @@ type route struct { func (r *Fiber) register(method string, args ...interface{}) { // Set if method is Use() midware var midware = method == "MIDWARE" + // Match any method if method == "ALL" || midware { method = "*" } + // Prepare possible variables var path string // We could have a path/prefix var handler func(*Ctx) // We could have a ctx handler + // Only 1 argument, so no path/prefix if len(args) == 1 { handler = args[0].(func(*Ctx)) @@ -52,49 +56,59 @@ func (r *Fiber) register(method string, args ...interface{}) { panic("Invalid path, must begin with slash '/' or wildcard '*'") } } + if midware && strings.Contains(path, "/:") { panic("You cannot use :params in Use()") } + // If Use() path == "/", match anything aka * if midware && path == "/" { path = "*" } + // If the route needs to match any path if path == "" || path == "*" || path == "/*" { - r.routes = append(r.routes, &route{method, path, midware, true, nil, nil, handler}) + r.routes = append(r.routes, &Route{method, path, midware, true, nil, nil, handler}) return } + // Get params from path params := getParams(path) - // If path has no params (simple path), we dont need regex (also for use()) + + // If path has no params (simple path), we don't need regex (also for use()) if midware || len(params) == 0 { - r.routes = append(r.routes, &route{method, path, midware, false, nil, nil, handler}) + r.routes = append(r.routes, &Route{method, path, midware, false, nil, nil, handler}) return } - // We have parametes, so we need to compile regix from the path + // We have parametes, so we need to compile regex from the path regex, err := getRegex(path) if err != nil { panic("Invalid url pattern: " + path) } + // Add regex + params to route - r.routes = append(r.routes, &route{method, path, midware, false, regex, params, handler}) + r.routes = append(r.routes, &Route{method, path, midware, false, regex, params, handler}) } // then try to match a route as efficient as possible. func (r *Fiber) handler(fctx *fasthttp.RequestCtx) { found := false + // get custom context from sync pool ctx := acquireCtx(fctx) + // get path and method from main context path := ctx.Path() method := ctx.Method() + // loop trough routes for _, route := range r.routes { // Skip route if method is not allowed if route.Method != "*" && route.Method != method { continue } + // First check if we match a wildcard or static path if route.Wildcard || route.Path == path { // if route.wildcard || (route.path == path && route.params == nil) { @@ -117,6 +131,7 @@ func (r *Fiber) handler(fctx *fasthttp.RequestCtx) { // continue to go to the next route continue } + // If route is Use() and path starts with route.path // aka strings.HasPrefix(route.path, path) if route.Midware && strings.HasPrefix(path, route.Path) { @@ -129,14 +144,17 @@ func (r *Fiber) handler(fctx *fasthttp.RequestCtx) { ctx.next = false continue } + // Skip route if regex does not exist if route.Regex == nil { continue } + // Skip route if regex does not match if !route.Regex.MatchString(path) { continue } + // If we have parameters, lets find the matches if len(route.Params) > 0 { matches := route.Regex.FindAllStringSubmatch(path, -1) @@ -146,23 +164,30 @@ func (r *Fiber) handler(fctx *fasthttp.RequestCtx) { ctx.values = matches[0][1:len(matches[0])] } } + found = true + // Set route pointer if user wants to call .Route() ctx.route = route + // Execute handler with context route.Handler(ctx) + // if next is not set, leave loop and release ctx if !ctx.next { break } + // set next to false for next iteration ctx.next = false } + // No routes found if !found { // Custom 404 handler? ctx.Status(404).Send("Not Found") } + // release context back into sync pool releaseCtx(ctx) } diff --git a/static.go b/static.go index d42cac903f7..46629ab5bcf 100644 --- a/static.go +++ b/static.go @@ -1,4 +1,4 @@ -// 🔌 Fiber is an Expressjs inspired web framework build on 🚀 Fasthttp. +// 🔌 Fiber is an Express.js inspired web framework build on 🚀 Fasthttp. // 📌 Please open an issue if you got suggestions or found a bug! // 🖥 https://github.com/gofiber/fiber @@ -19,6 +19,7 @@ func (r *Fiber) Static(args ...string) { wildcard := false // enable / disable gzipping somewhere? gzip := true + if len(args) == 1 { root = args[0] } else if len(args) == 2 { @@ -28,36 +29,44 @@ func (r *Fiber) Static(args ...string) { prefix = "/" + prefix } } + // Check if wildcard for single files if prefix == "*" || prefix == "/*" { wildcard = true } + // Lets get all files from root files, _, err := getFiles(root) if err != nil { panic(err) } + // ./static/compiled => static/compiled mount := filepath.Clean(root) + // Loop over all files for _, file := range files { // Ignore the .gzipped files by fasthttp if strings.Contains(file, ".fasthttp.gz") { continue } + // Time to create a fake path for the route match // static/index.html => /index.html path := filepath.Join(prefix, strings.Replace(file, mount, "", 1)) + // Store original file path to use in ctx handler filePath := file + // If the file is an index.html, bind the prefix to index.html directly if filepath.Base(filePath) == "index.html" || filepath.Base(filePath) == "index.htm" { - r.routes = append(r.routes, &route{"GET", prefix, wildcard, false, nil, nil, func(c *Ctx) { + r.routes = append(r.routes, &Route{"GET", prefix, wildcard, false, nil, nil, func(c *Ctx) { c.SendFile(filePath, gzip) }}) } + // Add the route + SendFile(filepath) to routes - r.routes = append(r.routes, &route{"GET", path, wildcard, false, nil, nil, func(c *Ctx) { + r.routes = append(r.routes, &Route{"GET", path, wildcard, false, nil, nil, func(c *Ctx) { c.SendFile(filePath, gzip) }}) } diff --git a/status.go b/status.go index 8aadaa87aa2..eeead617d93 100644 --- a/status.go +++ b/status.go @@ -1,4 +1,4 @@ -// 🔌 Fiber is an Expressjs inspired web framework build on 🚀 Fasthttp. +// 🔌 Fiber is an Express.js inspired web framework build on 🚀 Fasthttp. // 📌 Please open an issue if you got suggestions or found a bug! // 🖥 https://github.com/gofiber/fiber diff --git a/types.go b/types.go index 99ef50c7bbb..7b6bc1f1106 100644 --- a/types.go +++ b/types.go @@ -1,4 +1,4 @@ -// 🔌 Fiber is an Expressjs inspired web framework build on 🚀 Fasthttp. +// 🔌 Fiber is an Express.js inspired web framework build on 🚀 Fasthttp. // 📌 Please open an issue if you got suggestions or found a bug! // 🖥 https://github.com/gofiber/fiber @@ -9,9 +9,9 @@ package fiber // common content types const ( - contentTypeJson = "application/json" + contentTypeJSON = "application/json" contentTypeJs = "application/javascript" - contentTypeXml = "application/xml" + contentTypeXML = "application/xml" contentTypeOctetStream = "application/octet-stream" ) diff --git a/utils.go b/utils.go index a41ebb34979..7d103286fd3 100644 --- a/utils.go +++ b/utils.go @@ -1,4 +1,4 @@ -// 🔌 Fiber is an Expressjs inspired web framework build on 🚀 Fasthttp. +// 🔌 Fiber is an Express.js inspired web framework build on 🚀 Fasthttp. // 📌 Please open an issue if you got suggestions or found a bug! // 🖥 https://github.com/gofiber/fiber @@ -29,6 +29,7 @@ func getParams(path string) (params []string) { } return params } + func getRegex(path string) (*regexp.Regexp, error) { pattern := "^" segments := strings.Split(path, "/") @@ -49,6 +50,7 @@ func getRegex(path string) (*regexp.Regexp, error) { regex, err := regexp.Compile(pattern) return regex, err } + func getFiles(root string) (files []string, isDir bool, err error) { err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if !info.IsDir() { @@ -60,6 +62,7 @@ func getFiles(root string) (files []string, isDir bool, err error) { }) return files, isDir, err } + func getType(ext string) (mime string) { if ext[0] == '.' { ext = ext[1:] @@ -70,12 +73,15 @@ func getType(ext string) (mime string) { } return mime } + func getStatus(status int) (msg string) { return statusMessages[status] } + func getString(b []byte) string { return *(*string)(unsafe.Pointer(&b)) } + func getBytes(s string) []byte { return *(*[]byte)(unsafe.Pointer(&s)) }