mirror of https://github.com/gofiber/fiber.git
v1.0.0-pre-release
parent
dfe1b87fc3
commit
2730e0c2ff
10
.travis.yml
10
.travis.yml
|
@ -1,10 +0,0 @@
|
|||
language: go
|
||||
go:
|
||||
- 1.3.3
|
||||
- 1.4.2
|
||||
- 1.5.1
|
||||
- release
|
||||
- tip
|
||||
|
||||
script:
|
||||
- go test -v ./...
|
|
@ -1,76 +0,0 @@
|
|||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
||||
level of experience, education, socio-economic status, nationality, personal
|
||||
appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at gofiber@protonmail.com. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see
|
||||
https://www.contributor-covenant.org/faq
|
33
README.md
33
README.md
|
@ -39,9 +39,11 @@ import "github.com/gofiber/fiber"
|
|||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
app.Get("/:name", func(c *fiber.Ctx) {
|
||||
c.Send("Hello, " + c.Params("name") + "!")
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
c.Send("Hello, World!")
|
||||
})
|
||||
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
|
@ -59,16 +61,17 @@ import "github.com/gofiber/fiber"
|
|||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Static("./public")
|
||||
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
Now, you can load the files that are in the public directory:
|
||||
```shell
|
||||
http://localhost:8080/images/gopher.png
|
||||
http://localhost:8080/css/style.css
|
||||
http://localhost:8080/js/jquery.js
|
||||
http://localhost:8080/hello.html
|
||||
http://localhost:8080/js/jquery.js
|
||||
http://localhost:8080/css/style.css
|
||||
```
|
||||
|
||||
## Middleware
|
||||
|
@ -80,17 +83,21 @@ import "github.com/gofiber/fiber"
|
|||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
app.Get("/api*", func(c *fiber.Ctx) {
|
||||
c.Locals("auth", "admin")
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
c.Set("random-header", "random-value")
|
||||
c.Write("1st route!\n")
|
||||
c.Next()
|
||||
})
|
||||
app.Get("/api/back-end/:action?", func(c *fiber.Ctx) {
|
||||
if c.Locals("auth") != "admin" {
|
||||
c.Status(403).Send("Forbidden")
|
||||
return
|
||||
}
|
||||
c.Send("Hello, Admin!")
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
c.Write("2nd route!\n")
|
||||
c.Next()
|
||||
})
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
c.Write("3rd route!\n")
|
||||
})
|
||||
|
||||
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
|
|
575
context.go
575
context.go
|
@ -8,23 +8,13 @@
|
|||
package fiber
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/json-iterator/go"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
// Ctx struct
|
||||
type Ctx struct {
|
||||
noCopy noCopy
|
||||
route *route
|
||||
next bool
|
||||
params *[]string
|
||||
|
@ -67,568 +57,3 @@ func releaseCtx(ctx *Ctx) {
|
|||
ctx.Fasthttp = nil
|
||||
ctxPool.Put(ctx)
|
||||
}
|
||||
|
||||
// Accepts :
|
||||
func (ctx *Ctx) Accepts(typ string) bool {
|
||||
accept := ctx.Get("Accept-Charset")
|
||||
if strings.Contains(accept, typ) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AcceptsCharsets :
|
||||
func (ctx *Ctx) AcceptsCharsets(charset string) bool {
|
||||
accept := ctx.Get("Accept-Charset")
|
||||
if strings.Contains(accept, charset) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AcceptsEncodings :
|
||||
func (ctx *Ctx) AcceptsEncodings(encoding string) bool {
|
||||
accept := ctx.Get("Accept-Encoding")
|
||||
if strings.Contains(accept, encoding) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AcceptsLanguages :
|
||||
func (ctx *Ctx) AcceptsLanguages(lang string) bool {
|
||||
accept := ctx.Get("Accept-Language")
|
||||
if strings.Contains(accept, lang) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Append :
|
||||
func (ctx *Ctx) Append(field string, values ...string) {
|
||||
newVal := ctx.Get(field)
|
||||
if len(values) > 0 {
|
||||
for i := range values {
|
||||
newVal = newVal + ", " + values[i]
|
||||
}
|
||||
}
|
||||
ctx.Set(field, newVal)
|
||||
}
|
||||
|
||||
// Attachment :
|
||||
func (ctx *Ctx) Attachment(name ...string) {
|
||||
if len(name) > 0 {
|
||||
filename := filepath.Base(name[0])
|
||||
ctx.Type(filepath.Ext(filename))
|
||||
ctx.Set("Content-Disposition", `attachment; filename="`+filename+`"`)
|
||||
return
|
||||
}
|
||||
ctx.Set("Content-Disposition", "attachment")
|
||||
}
|
||||
|
||||
// BaseUrl :
|
||||
func (ctx *Ctx) BaseUrl() string {
|
||||
return ctx.Protocol() + "://" + ctx.Hostname()
|
||||
}
|
||||
|
||||
// BasicAuth :
|
||||
func (ctx *Ctx) BasicAuth() (user, pass string, ok bool) {
|
||||
auth := ctx.Get("Authorization")
|
||||
if auth == "" {
|
||||
return
|
||||
}
|
||||
const prefix = "Basic "
|
||||
// Case insensitive prefix match.
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return
|
||||
}
|
||||
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cs := b2s(c)
|
||||
s := strings.IndexByte(cs, ':')
|
||||
if s < 0 {
|
||||
return
|
||||
}
|
||||
return cs[:s], cs[s+1:], true
|
||||
}
|
||||
|
||||
// Body :
|
||||
func (ctx *Ctx) Body(args ...interface{}) string {
|
||||
if len(args) == 0 {
|
||||
return b2s(ctx.Fasthttp.Request.Body())
|
||||
}
|
||||
if len(args) == 1 {
|
||||
switch arg := args[0].(type) {
|
||||
case string:
|
||||
return b2s(ctx.Fasthttp.Request.PostArgs().Peek(arg))
|
||||
case func(string, string):
|
||||
ctx.Fasthttp.Request.PostArgs().VisitAll(func(k []byte, v []byte) {
|
||||
arg(b2s(k), b2s(v))
|
||||
})
|
||||
default:
|
||||
return b2s(ctx.Fasthttp.Request.Body())
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ClearCookie :
|
||||
func (ctx *Ctx) ClearCookie(name ...string) {
|
||||
if len(name) == 0 {
|
||||
ctx.Fasthttp.Request.Header.VisitAllCookie(func(k, v []byte) {
|
||||
fmt.Println(b2s(k), b2s(v))
|
||||
ctx.Fasthttp.Response.Header.DelClientCookie(b2s(k))
|
||||
})
|
||||
} else if len(name) > 0 {
|
||||
for i := range name {
|
||||
ctx.Fasthttp.Response.Header.DelClientCookie(name[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cookie :
|
||||
func (ctx *Ctx) Cookie(key, value string, options ...interface{}) {
|
||||
cook := &fasthttp.Cookie{}
|
||||
cook.SetKey(key)
|
||||
cook.SetValue(value)
|
||||
if len(options) > 0 {
|
||||
switch opt := options[0].(type) {
|
||||
case *Cookie:
|
||||
if opt.Expire > 0 {
|
||||
cook.SetExpire(time.Unix(int64(opt.Expire), 0))
|
||||
}
|
||||
if opt.MaxAge > 0 {
|
||||
cook.SetMaxAge(opt.MaxAge)
|
||||
}
|
||||
if opt.Domain != "" {
|
||||
cook.SetDomain(opt.Domain)
|
||||
}
|
||||
if opt.Path != "" {
|
||||
cook.SetPath(opt.Path)
|
||||
}
|
||||
if opt.HttpOnly {
|
||||
cook.SetHTTPOnly(opt.HttpOnly)
|
||||
}
|
||||
if opt.Secure {
|
||||
cook.SetSecure(opt.Secure)
|
||||
}
|
||||
if opt.SameSite != "" {
|
||||
sameSite := fasthttp.CookieSameSiteDisabled
|
||||
if strings.EqualFold(opt.SameSite, "lax") {
|
||||
sameSite = fasthttp.CookieSameSiteLaxMode
|
||||
} else if strings.EqualFold(opt.SameSite, "strict") {
|
||||
sameSite = fasthttp.CookieSameSiteStrictMode
|
||||
} else if strings.EqualFold(opt.SameSite, "none") {
|
||||
sameSite = fasthttp.CookieSameSiteNoneMode
|
||||
} else {
|
||||
sameSite = fasthttp.CookieSameSiteDefaultMode
|
||||
}
|
||||
cook.SetSameSite(sameSite)
|
||||
}
|
||||
default:
|
||||
panic("Invalid cookie options")
|
||||
}
|
||||
}
|
||||
ctx.Fasthttp.Response.Header.SetCookie(cook)
|
||||
}
|
||||
|
||||
// Cookies :
|
||||
func (ctx *Ctx) Cookies(args ...interface{}) string {
|
||||
if len(args) == 0 {
|
||||
//return b2s(ctx.Fasthttp.Response.Header.Peek("Cookie"))
|
||||
return ctx.Get("Cookie")
|
||||
}
|
||||
switch arg := args[0].(type) {
|
||||
case string:
|
||||
return b2s(ctx.Fasthttp.Request.Header.Cookie(arg))
|
||||
case func(string, string):
|
||||
ctx.Fasthttp.Request.Header.VisitAllCookie(func(k, v []byte) {
|
||||
arg(b2s(k), b2s(v))
|
||||
})
|
||||
default:
|
||||
panic("Argument must be a string or func(string, string)")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Download :
|
||||
func (ctx *Ctx) Download(file string, name ...string) {
|
||||
filename := filepath.Base(file)
|
||||
if len(name) > 0 {
|
||||
filename = name[0]
|
||||
}
|
||||
ctx.Set("Content-Disposition", "attachment; filename="+filename)
|
||||
ctx.SendFile(file)
|
||||
}
|
||||
|
||||
// End TODO
|
||||
func (ctx *Ctx) End() {
|
||||
|
||||
}
|
||||
|
||||
// Format TODO
|
||||
func (ctx *Ctx) Format() {
|
||||
|
||||
}
|
||||
|
||||
// FormFile :
|
||||
func (ctx *Ctx) FormFile(key string) (*multipart.FileHeader, error) {
|
||||
return ctx.Fasthttp.FormFile(key)
|
||||
}
|
||||
|
||||
// FormValue :
|
||||
func (ctx *Ctx) FormValue(key string) string {
|
||||
return b2s(ctx.Fasthttp.FormValue(key))
|
||||
}
|
||||
|
||||
// Fresh TODO https://expressjs.com/en/4x/api.html#req.fresh
|
||||
func (ctx *Ctx) Fresh() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Get :
|
||||
func (ctx *Ctx) Get(key string) string {
|
||||
// https://en.wikipedia.org/wiki/HTTP_referer
|
||||
if key == "referrer" {
|
||||
key = "referer"
|
||||
}
|
||||
return b2s(ctx.Fasthttp.Request.Header.Peek(key))
|
||||
}
|
||||
|
||||
// HeadersSent TODO
|
||||
func (ctx *Ctx) HeadersSent() {
|
||||
|
||||
}
|
||||
|
||||
// Hostname :
|
||||
func (ctx *Ctx) Hostname() string {
|
||||
return b2s(ctx.Fasthttp.URI().Host())
|
||||
}
|
||||
|
||||
// Ip :
|
||||
func (ctx *Ctx) Ip() string {
|
||||
return ctx.Fasthttp.RemoteIP().String()
|
||||
}
|
||||
|
||||
// Ips https://expressjs.com/en/4x/api.html#req.ips
|
||||
func (ctx *Ctx) Ips() []string {
|
||||
ips := strings.Split(ctx.Get("X-Forwarded-For"), ",")
|
||||
for i := range ips {
|
||||
ips[i] = strings.TrimSpace(ips[i])
|
||||
}
|
||||
return ips
|
||||
}
|
||||
|
||||
// Is :
|
||||
func (ctx *Ctx) Is(ext string) bool {
|
||||
if ext[0] != '.' {
|
||||
ext = "." + ext
|
||||
}
|
||||
exts, _ := mime.ExtensionsByType(ctx.Get("Content-Type"))
|
||||
if len(exts) > 0 {
|
||||
for _, item := range exts {
|
||||
if item == ext {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Json :
|
||||
func (ctx *Ctx) Json(v interface{}) error {
|
||||
raw, err := jsoniter.Marshal(&v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx.Set("Content-Type", "application/json")
|
||||
ctx.Fasthttp.Response.SetBodyString(b2s(raw))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Jsonp :
|
||||
func (ctx *Ctx) Jsonp(v interface{}, cb ...string) error {
|
||||
raw, err := jsoniter.Marshal(&v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
if len(cb) > 0 {
|
||||
builder.Write(s2b(cb[0]))
|
||||
} else {
|
||||
builder.Write([]byte("callback"))
|
||||
}
|
||||
builder.Write([]byte("("))
|
||||
builder.Write(raw)
|
||||
builder.Write([]byte(");"))
|
||||
|
||||
// Create buffer with length of json + cbname + ( );
|
||||
// buf := make([]byte, len(raw)+len(cbName)+3)
|
||||
//
|
||||
// count := 0
|
||||
// count += copy(buf[count:], cbName)
|
||||
// count += copy(buf[count:], "(")
|
||||
// count += copy(buf[count:], raw)
|
||||
// count += copy(buf[count:], ");")
|
||||
|
||||
ctx.Set("X-Content-Type-Options", "nosniff")
|
||||
ctx.Set("Content-Type", "application/javascript")
|
||||
ctx.Fasthttp.Response.SetBodyString(builder.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
// Links :
|
||||
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, ",")
|
||||
ctx.Set("Link", h)
|
||||
}
|
||||
}
|
||||
|
||||
// Locals :
|
||||
func (ctx *Ctx) Locals(key string, val ...interface{}) interface{} {
|
||||
if len(val) == 0 {
|
||||
return ctx.Fasthttp.UserValue(key)
|
||||
} else {
|
||||
ctx.Fasthttp.SetUserValue(key, val[0])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Location :
|
||||
func (ctx *Ctx) Location(path string) {
|
||||
ctx.Set("Location", path)
|
||||
}
|
||||
|
||||
// Method :
|
||||
func (ctx *Ctx) Method() string {
|
||||
return b2s(ctx.Fasthttp.Request.Header.Method())
|
||||
}
|
||||
|
||||
// MultipartForm :
|
||||
func (ctx *Ctx) MultipartForm() (*multipart.Form, error) {
|
||||
return ctx.Fasthttp.MultipartForm()
|
||||
}
|
||||
|
||||
// Next :
|
||||
func (ctx *Ctx) Next() {
|
||||
ctx.next = true
|
||||
ctx.params = nil
|
||||
ctx.values = nil
|
||||
}
|
||||
|
||||
// OriginalUrl :
|
||||
func (ctx *Ctx) OriginalUrl() string {
|
||||
return b2s(ctx.Fasthttp.Request.Header.RequestURI())
|
||||
}
|
||||
|
||||
// Params :
|
||||
func (ctx *Ctx) Params(key string) string {
|
||||
if ctx.params == nil {
|
||||
return ""
|
||||
}
|
||||
for i := 0; i < len(*ctx.params); i++ {
|
||||
if (*ctx.params)[i] == key {
|
||||
return ctx.values[i]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Path :
|
||||
func (ctx *Ctx) Path() string {
|
||||
return b2s(ctx.Fasthttp.URI().Path())
|
||||
}
|
||||
|
||||
// Protocol :
|
||||
func (ctx *Ctx) Protocol() string {
|
||||
if ctx.Fasthttp.IsTLS() {
|
||||
return "https"
|
||||
}
|
||||
return "http"
|
||||
}
|
||||
|
||||
// Query :
|
||||
func (ctx *Ctx) Query(key string) string {
|
||||
return b2s(ctx.Fasthttp.QueryArgs().Peek(key))
|
||||
}
|
||||
|
||||
// Range TODO
|
||||
func (ctx *Ctx) Range() {
|
||||
|
||||
}
|
||||
|
||||
// Redirect :
|
||||
func (ctx *Ctx) Redirect(path string, status ...int) {
|
||||
ctx.Set("Location", path)
|
||||
if len(status) > 0 {
|
||||
ctx.Status(status[0])
|
||||
} else {
|
||||
ctx.Status(302)
|
||||
}
|
||||
}
|
||||
|
||||
// Render TODO https://expressjs.com/en/4x/api.html#res.render
|
||||
func (ctx *Ctx) Render() {
|
||||
|
||||
}
|
||||
|
||||
// Route : Only use in debugging
|
||||
func (ctx *Ctx) Route() (s struct {
|
||||
Method string
|
||||
Path string
|
||||
Wildcard bool
|
||||
Regex *regexp.Regexp
|
||||
Params []string
|
||||
Values []string
|
||||
Handler func(*Ctx)
|
||||
}) {
|
||||
s.Method = ctx.route.method
|
||||
s.Path = ctx.route.path
|
||||
s.Wildcard = ctx.route.wildcard
|
||||
s.Regex = ctx.route.regex
|
||||
s.Params = ctx.route.params
|
||||
s.Values = ctx.values
|
||||
s.Handler = ctx.route.handler
|
||||
return
|
||||
}
|
||||
|
||||
// Secure :
|
||||
func (ctx *Ctx) Secure() bool {
|
||||
return ctx.Fasthttp.IsTLS()
|
||||
}
|
||||
|
||||
// Send :
|
||||
func (ctx *Ctx) Send(args ...interface{}) {
|
||||
|
||||
// https://github.com/valyala/fasthttp/blob/master/http.go#L490
|
||||
if len(args) != 1 {
|
||||
panic("To many arguments!")
|
||||
}
|
||||
switch body := args[0].(type) {
|
||||
case string:
|
||||
//ctx.Fasthttp.Response.SetBodyRaw(s2b(body))
|
||||
ctx.Fasthttp.Response.SetBodyString(body)
|
||||
case []byte:
|
||||
//ctx.Fasthttp.Response.SetBodyRaw(body)
|
||||
ctx.Fasthttp.Response.SetBodyString(b2s(body))
|
||||
default:
|
||||
panic("body must be a string or []byte")
|
||||
}
|
||||
}
|
||||
|
||||
// SendBytes : Same as Send() but without type assertion
|
||||
func (ctx *Ctx) SendBytes(body []byte) {
|
||||
ctx.Fasthttp.Response.SetBodyString(b2s(body))
|
||||
}
|
||||
|
||||
// SendFile :
|
||||
func (ctx *Ctx) SendFile(file string, gzip ...bool) {
|
||||
// Disable gzipping
|
||||
if len(gzip) > 0 && !gzip[0] {
|
||||
fasthttp.ServeFileUncompressed(ctx.Fasthttp, file)
|
||||
}
|
||||
fasthttp.ServeFile(ctx.Fasthttp, file)
|
||||
// https://github.com/valyala/fasthttp/blob/master/fs.go#L81
|
||||
//ctx.Type(filepath.Ext(path))
|
||||
//ctx.Fasthttp.SendFile(path)
|
||||
}
|
||||
|
||||
// SendStatus :
|
||||
func (ctx *Ctx) SendStatus(status int) {
|
||||
ctx.Status(status)
|
||||
// Only set status body when there is no response body
|
||||
if len(ctx.Fasthttp.Response.Body()) == 0 {
|
||||
msg := statusMessages[status]
|
||||
if msg != "" {
|
||||
ctx.Fasthttp.Response.SetBodyString(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SendString : Same as Send() but without type assertion
|
||||
func (ctx *Ctx) SendString(body string) {
|
||||
ctx.Fasthttp.Response.SetBodyString(body)
|
||||
}
|
||||
|
||||
// Set :
|
||||
func (ctx *Ctx) Set(key string, val string) {
|
||||
ctx.Fasthttp.Response.Header.SetCanonical(s2b(key), s2b(val))
|
||||
}
|
||||
|
||||
// SignedCookies TODO
|
||||
func (ctx *Ctx) SignedCookies() {
|
||||
|
||||
}
|
||||
|
||||
// Stale TODO https://expressjs.com/en/4x/api.html#req.fresh
|
||||
func (ctx *Ctx) Stale() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Status :
|
||||
func (ctx *Ctx) Status(status int) *Ctx {
|
||||
ctx.Fasthttp.Response.SetStatusCode(status)
|
||||
return ctx
|
||||
}
|
||||
|
||||
// Subdomains :
|
||||
func (ctx *Ctx) Subdomains() (subs []string) {
|
||||
subs = strings.Split(ctx.Hostname(), ".")
|
||||
subs = subs[:len(subs)-2]
|
||||
return subs
|
||||
}
|
||||
|
||||
// Type :
|
||||
func (ctx *Ctx) Type(ext string) *Ctx {
|
||||
if ext[0] != '.' {
|
||||
ext = "." + ext
|
||||
}
|
||||
m := mime.TypeByExtension(ext)
|
||||
ctx.Set("Content-Type", m)
|
||||
return ctx
|
||||
}
|
||||
|
||||
// Vary :
|
||||
func (ctx *Ctx) Vary(field ...string) {
|
||||
vary := ctx.Get("Vary")
|
||||
for _, f := range field {
|
||||
if !strings.Contains(vary, f) {
|
||||
vary += ", " + f
|
||||
}
|
||||
}
|
||||
if len(field) > 0 {
|
||||
ctx.Set("Vary", vary)
|
||||
}
|
||||
}
|
||||
|
||||
// Write :
|
||||
func (ctx *Ctx) Write(args ...interface{}) {
|
||||
if len(args) == 0 {
|
||||
panic("Missing body")
|
||||
}
|
||||
switch body := args[0].(type) {
|
||||
case string:
|
||||
ctx.Fasthttp.Response.SetBodyString(body)
|
||||
case []byte:
|
||||
ctx.Fasthttp.Response.AppendBodyString(b2s(body))
|
||||
default:
|
||||
panic("body must be a string or []byte")
|
||||
}
|
||||
}
|
||||
|
||||
// Xhr :
|
||||
func (ctx *Ctx) Xhr() bool {
|
||||
return ctx.Get("X-Requested-With") == "XMLHttpRequest"
|
||||
}
|
||||
|
|
|
@ -1,63 +1,111 @@
|
|||
# Application
|
||||
The app object conventionally denotes the Fiber application.
|
||||
The app instance conventionally denotes the Fiber application.
|
||||
|
||||
#### Initialize
|
||||
Creates an Fiber instance name "app"
|
||||
#### New
|
||||
Creates an new Fiber instance that we named "**app**".
|
||||
```go
|
||||
app := fiber.New()
|
||||
// Optional fiber settings
|
||||
// Sends the "Server" header, disabled by default
|
||||
app.Server = ""
|
||||
// Hides fiber banner, enabled by default
|
||||
app.Banner = true
|
||||
// Enable prefork
|
||||
// https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
|
||||
app.Prefork = false
|
||||
// ...
|
||||
// Application logic here...
|
||||
// ...
|
||||
app.Listen(8080)
|
||||
```
|
||||
|
||||
#### TLS
|
||||
To enable TLS you need to provide a certkey and certfile.
|
||||
#### Server
|
||||
Fiber by default does not send a [server header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server), but you can enable this by changing the server value.
|
||||
```go
|
||||
// Enable TLS
|
||||
app := fiber.New()
|
||||
|
||||
app.CertKey("./cert.key")
|
||||
app.CertFile("./cert.pem")
|
||||
app.Server = "Windows 95"
|
||||
// => Server: Windows 95
|
||||
|
||||
app.Listen(443)
|
||||
app.Listen(8080)
|
||||
```
|
||||
#### Fasthttp
|
||||
You can pass some Fasthttp server settings via the Fiber instance.
|
||||
Make sure that you set these settings before calling the [Listen](#listen) method. You can find the description of each property in [Fasthttp server settings](https://github.com/valyala/fasthttp/blob/master/server.go#L150)
|
||||
|
||||
!>Only change these settings if you know what you are doing.
|
||||
#### Banner
|
||||
When you launch your Fiber application, the console will print a banner containing the package version and listening port. This is enabled by default, disable it by setting the Banner value to false.
|
||||
|
||||

|
||||
|
||||
```go
|
||||
app := fiber.New()
|
||||
|
||||
app.Fasthttp.Concurrency = 256 * 1024
|
||||
app.Fasthttp.DisableKeepAlive = false
|
||||
app.Fasthttp.ReadBufferSize = 4096
|
||||
app.Fasthttp.WriteBufferSize = 4096
|
||||
app.Fasthttp.ReadTimeout = 0
|
||||
app.Fasthttp.WriteTimeout = 0
|
||||
app.Fasthttp.IdleTimeout = 0
|
||||
app.Fasthttp.MaxConnsPerIP = 0
|
||||
app.Fasthttp.MaxRequestsPerConn = 0
|
||||
app.Fasthttp.TCPKeepalive = false
|
||||
app.Fasthttp.TCPKeepalivePeriod = 0
|
||||
app.Fasthttp.MaxRequestBodySize = 4 * 1024 * 1024
|
||||
app.Fasthttp.ReduceMemoryUsage = false
|
||||
app.Fasthttp.GetOnly = false
|
||||
app.Fasthttp.DisableHeaderNamesNormalizing = false
|
||||
app.Fasthttp.SleepWhenConcurrencyLimitsExceeded = 0
|
||||
app.Fasthttp.NoDefaultContentType = false
|
||||
app.Fasthttp.KeepHijackedConns = false
|
||||
app.Banner = false
|
||||
|
||||
app.Listen(8080)
|
||||
```
|
||||
|
||||
#### Engine
|
||||
You can edit some of the Fasthttp server settings via the Fiber instance.
|
||||
Make sure that you set these settings before calling the [Listen](#listen) method. You can find the description of each value in [Fasthttp server settings](https://github.com/valyala/fasthttp/blob/master/server.go#L150)
|
||||
|
||||
**Only change these settings if you know what you are doing.**
|
||||
```go
|
||||
app := fiber.New()
|
||||
|
||||
// These are the default fasthttp settings
|
||||
app.Engine.Concurrency = 256 * 1024
|
||||
app.Engine.DisableKeepAlive = false
|
||||
app.Engine.ReadBufferSize = 4096
|
||||
app.Engine.WriteBufferSize = 4096
|
||||
app.Engine.ReadTimeout = 0
|
||||
app.Engine.WriteTimeout = 0
|
||||
app.Engine.IdleTimeout = 0
|
||||
app.Engine.MaxConnsPerIP = 0
|
||||
app.Engine.MaxRequestsPerConn = 0
|
||||
app.Engine.TCPKeepalive = false
|
||||
app.Engine.TCPKeepalivePeriod = 0
|
||||
app.Engine.MaxRequestBodySize = 4 * 1024 * 1024
|
||||
app.Engine.ReduceMemoryUsage = false
|
||||
app.Engine.GetOnly = false
|
||||
app.Engine.DisableHeaderNamesNormalizing = false
|
||||
app.Engine.SleepWhenConcurrencyLimitsExceeded = 0
|
||||
app.Engine.NoDefaultContentType = false
|
||||
app.Engine.KeepHijackedConns = false
|
||||
|
||||
// Start your app
|
||||
app.Listen(8080)
|
||||
```
|
||||
|
||||
#### Prefork
|
||||
Prefork enables use of the **[SO_REUSEPORT](https://lwn.net/Articles/542629/)** socket option, which is available in newer versions of many operating systems, including DragonFly BSD and Linux (kernel version 3.9 and later). This will spawn multiple go processes listening on the same port.
|
||||
|
||||
NGINX has a great article about [Socket Sharding](https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/), these pictures are taken from the same article.
|
||||
|
||||
<img src="https://cdn.wp.nginx.com/wp-content/uploads/2015/05/Slack-for-iOS-Upload-1-e1432652484191.png" style="width: 50%;float: left;"/>
|
||||
<img src="https://cdn.wp.nginx.com/wp-content/uploads/2015/05/Slack-for-iOS-Upload-e1432652376641.png" style="width: 50%;float: left;"/>
|
||||
<div style="clear:both"></div>
|
||||
|
||||
You can enable the **prefork** feature by adding the **-prefork** flag.
|
||||
|
||||
```bash
|
||||
./server -prefork
|
||||
```
|
||||
|
||||
Or enable the **Prefork** option in your app.
|
||||
```go
|
||||
app := fiber.New()
|
||||
|
||||
app.Prefork = true
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
c.Send(fmt.Sprintf("Hi, I'm worker #%v", os.Getpid()))
|
||||
// => Hi, I'm worker #16858
|
||||
// => Hi, I'm worker #16877
|
||||
// => Hi, I'm worker #16895
|
||||
})
|
||||
|
||||
app.Listen(8080)
|
||||
```
|
||||
|
||||
#### Methods
|
||||
Routes an HTTP request, where METHOD is the HTTP method 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. See Routing methods below for the complete list.
|
||||
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))
|
||||
app.Get(path string, handler func(*Ctx))
|
||||
|
||||
// Methods
|
||||
app.Connect(...)
|
||||
app.Delete(...)
|
||||
app.Get(...)
|
||||
|
@ -67,45 +115,27 @@ app.Patch(...)
|
|||
app.Post(...)
|
||||
app.Put(...)
|
||||
app.Trace(...)
|
||||
// Matches all HTTP verbs
|
||||
// Use & All are the same function
|
||||
app.Use(...)
|
||||
|
||||
// Matches all HTTP verbs, Use refers to All
|
||||
app.All(...)
|
||||
```
|
||||
|
||||
#### Prefork
|
||||
Prefork enables use of the SO_REUSEPORT socket option, which is available in newer versions of many operating systems, including DragonFly BSD and Linux (kernel version 3.9 and later).
|
||||
This will spawn multiple go processes depending on how many cpu cores you have and reuse the port.
|
||||
Read more here [SO_REUSEPORT](https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/)
|
||||
```bash
|
||||
go run main.go -prefork
|
||||
# Or on build
|
||||
./main -prefork
|
||||
```
|
||||
|
||||
You can also enable preforking within the application.
|
||||
```go
|
||||
// Function signature
|
||||
app.Prefork = true
|
||||
|
||||
// Example
|
||||
app := fiber.New()
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
c.Send(fmt.Printf("Conn accepted via PID%v", os.Getpid()))
|
||||
})
|
||||
app.Listen(8080)
|
||||
app.Use(...)
|
||||
```
|
||||
|
||||
#### Listen
|
||||
Binds and listens for connections on the specified host and port.
|
||||
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(port int, addr ...string)
|
||||
app.Listen(address interface{}, tls ...string)
|
||||
|
||||
|
||||
// Example
|
||||
// Examples
|
||||
app.Listen(8080)
|
||||
app.Listen(8080, "127.0.0.1")
|
||||
app.Listen("8080")
|
||||
app.Listen(":8080")
|
||||
app.Listen("127.0.0.1:8080")
|
||||
|
||||
// Enable TLS/HTTPS
|
||||
app.Listen(443, "server.crt", "server.key")
|
||||
app.Listen("127.0.0.1:443", "server.crt", "server.key")
|
||||
```
|
||||
|
||||
|
||||
|
|
|
@ -57,3 +57,5 @@ If we enable http pipelining, test result as below:
|
|||
CPU-Bound Test
|
||||
|
||||

|
||||
|
||||
*Caught a mistake? [Edit this page on GitHub!](https://github.com/Fenny/fiber/blob/master/docs/benchmarks.md)*
|
||||
|
|
|
@ -90,8 +90,8 @@ app.Get("/", func(c *fiber.Ctx) {
|
|||
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, value string)
|
||||
c.Append(field, values ...string)
|
||||
|
||||
// Example
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
// Let's see if the Link header exist
|
||||
|
@ -111,8 +111,7 @@ app.Get("/", func(c *fiber.Ctx) {
|
|||
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()
|
||||
c.Attachment(file string)
|
||||
c.Attachment(file ...string)
|
||||
|
||||
// Example
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
|
@ -298,7 +297,7 @@ app.Get("/", func(c *fiber.Ctx) {
|
|||
```
|
||||
|
||||
#### !End
|
||||
!> Planned for V1
|
||||
!> Planned for v2.0.0
|
||||
|
||||
#### Fasthttp
|
||||
You can still access and use all Fasthttp methods and properties.
|
||||
|
@ -318,7 +317,7 @@ app.Get("/", func(c *fiber.Ctx) {
|
|||
```
|
||||
|
||||
#### !Format
|
||||
!> Planned for V1
|
||||
!> Planned for v2.0.0
|
||||
|
||||
#### FormFile
|
||||
MultipartForm files can be retrieved by name, the first file from the given key is returned.
|
||||
|
@ -354,7 +353,7 @@ app.Post("/", func(c *fiber.Ctx) {
|
|||
```
|
||||
|
||||
#### !Fresh
|
||||
!> Planned for V1
|
||||
!> Planned for v2.0.0
|
||||
|
||||
#### Get
|
||||
Returns the HTTP response header specified by field. The match is case-insensitive.
|
||||
|
@ -376,7 +375,7 @@ app.Get("/", func(c *fiber.Ctx) {
|
|||
```
|
||||
|
||||
#### !HeadersSent
|
||||
!> Planned for V1
|
||||
!> Planned for v2.0.0
|
||||
|
||||
#### Hostname
|
||||
Contains the hostname derived from the Host HTTP header.
|
||||
|
@ -721,7 +720,7 @@ app.Get("/", func(c *fiber.Ctx) {
|
|||
```
|
||||
|
||||
#### !Range
|
||||
!> Planned for V1
|
||||
!> 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”.
|
||||
|
@ -740,7 +739,7 @@ app.Get("/", func(c *fiber.Ctx) {
|
|||
```
|
||||
|
||||
#### !Render
|
||||
!> Planned for V1
|
||||
!> Planned for v2.0.0
|
||||
|
||||
#### Route
|
||||
Contains the currently-matched route struct, **only use this for debugging**.
|
||||
|
@ -882,10 +881,10 @@ app.Get("/", func(c *fiber.Ctx) {
|
|||
```
|
||||
|
||||
#### !SignedCookies
|
||||
!> Planned for V1
|
||||
!> Planned for v2.0.0
|
||||
|
||||
#### !Stale
|
||||
!> Planned for V1
|
||||
!> Planned for v2.0.0
|
||||
|
||||
#### Status
|
||||
Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.
|
||||
|
|
|
@ -8,27 +8,20 @@ package main
|
|||
import "github.com/fenny/fiber"
|
||||
|
||||
func main() {
|
||||
// lol
|
||||
app := fiber.New()
|
||||
|
||||
app.Post("/", func(c *fiber.Ctx) {
|
||||
// Parse the multipart form
|
||||
if form := c.MultipartForm(); form != nil {
|
||||
// => *multipart.Form
|
||||
|
||||
// Get all files from "documents" key
|
||||
files := form.File["documents"]
|
||||
// => []*multipart.FileHeader
|
||||
|
||||
// Loop trough files
|
||||
for _, file := range files {
|
||||
fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0])
|
||||
// => "tutorial.pdf" 360641 "application/pdf"
|
||||
|
||||
// Save the files to disk
|
||||
c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
|
||||
// Saves the file to disk
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
|
@ -42,14 +35,13 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
app.Static("./static")
|
||||
app.Get(notFound)
|
||||
app.Use(func (c *fiber.Ctx) {
|
||||
c.SendStatus(404)
|
||||
// => 404 "Not Found"
|
||||
})
|
||||
|
||||
app.Listen(8080)
|
||||
}
|
||||
|
||||
func notFound(c *fiber.Ctx) {
|
||||
c.Status(404).Send("Not Found")
|
||||
}
|
||||
```
|
||||
#### Static Caching
|
||||
```go
|
||||
|
@ -59,14 +51,14 @@ import "github.com/fenny/fiber"
|
|||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
app.Get(cacheControl)
|
||||
app.Static("./static")
|
||||
app.Listen(8080)
|
||||
}
|
||||
|
||||
func cacheControl(c *fiber.Ctx) {
|
||||
c.Set("Cache-Control", "max-age=2592000, public")
|
||||
c.Next()
|
||||
app.Get(func(c *fiber.Ctx) {
|
||||
c.Set("Cache-Control", "max-age=2592000, public")
|
||||
c.Next()
|
||||
})
|
||||
app.Static("./static")
|
||||
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
#### Enable CORS
|
||||
|
@ -78,20 +70,17 @@ import "./fiber"
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.All("/api", enableCors)
|
||||
app.Get("/api", apiHandler)
|
||||
app.Use("/api", func(c *fiber.Ctx) {
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Headers", "X-Requested-With")
|
||||
c.Next()
|
||||
})
|
||||
app.Get("/api", func(c *fiber.Ctx) {
|
||||
c.Send("Hi, I'm API!")
|
||||
})
|
||||
|
||||
app.Listen(8080)
|
||||
}
|
||||
|
||||
func enableCors(c *fiber.Ctx) {
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Headers", "X-Requested-With")
|
||||
c.Next()
|
||||
}
|
||||
func apiHandler(c *fiber.Ctx) {
|
||||
c.Send("Hi, I'm API!")
|
||||
}
|
||||
```
|
||||
#### Returning JSON
|
||||
```go
|
||||
|
@ -106,20 +95,36 @@ type Data struct {
|
|||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/json", func(c *fiber.Ctx) {
|
||||
data := SomeData{
|
||||
Name: "John",
|
||||
Age: 20,
|
||||
data := Data{
|
||||
Name: "John", `json:"name"`
|
||||
Age: 20, `json:"age"`
|
||||
}
|
||||
c.Json(data)
|
||||
// or
|
||||
err := c.Json(data)
|
||||
if err != nil {
|
||||
c.Send("Something went wrong!")
|
||||
c.SendStatus(500)
|
||||
}
|
||||
})
|
||||
|
||||
app.Listen(8080)
|
||||
}
|
||||
```
|
||||
#### Enable TLS/HTTTPS
|
||||
```go
|
||||
package main
|
||||
|
||||
import "./fiber"
|
||||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) {
|
||||
c.Send(c.Protocol()) // => "https"
|
||||
})
|
||||
|
||||
app.Listen(443, "server.crt", "server.key")
|
||||
}
|
||||
```
|
||||
|
||||
*Caught a mistake? [Edit this page on GitHub!](https://github.com/Fenny/fiber/blob/master/docs/examples.md)*
|
||||
|
|
|
@ -6,7 +6,7 @@
|
|||
[](https://gitter.im/FiberGo/community)
|
||||
<br>
|
||||
# Getting started
|
||||
!>**IMPORTANT: Do not use this in production, API might change before we release v1.0.0!**
|
||||
!>**IMPORTANT: Always use versioning control using [go.mod](https://blog.golang.org/using-go-modules) to avoid breaking API changes!**
|
||||
|
||||
**[Fiber](https://github.com/gofiber/fiber)** is a router framework build on top of [FastHTTP](https://github.com/valyala/fasthttp), the fastest HTTP package for **[Go](https://golang.org/doc/)**.<br>
|
||||
This library is inspired by [Express](https://expressjs.com/en/4x/api.html), one of the most populair and well known web framework for **[Nodejs](https://nodejs.org/en/about/)**.
|
||||
|
@ -54,9 +54,9 @@ app.Method(path string, func(*fiber.Ctx))
|
|||
```
|
||||
|
||||
* **app** is an instance of **[Fiber](#hello-world)**.
|
||||
* **Method** is an [HTTP request method](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods), in capitalization: Get, Put, Post etc
|
||||
* **path string** is a path or prefix (for static files) on the server.
|
||||
* **func(*fiber.Ctx)** is a function executed when the route is matched.
|
||||
* **Method** is an [HTTP request method](application?id=methods), in capitalization: Get, Put, Post etc
|
||||
* **path string** is a path on the server.
|
||||
* **func(*fiber.Ctx)** is a function containing the [Context](/context) executed when the route is matched.
|
||||
|
||||
This tutorial assumes that an instance of fiber named app is created and the server is running. If you are not familiar with creating an app and starting it, see the [Hello world](#hello-world) example.
|
||||
|
||||
|
@ -67,19 +67,28 @@ app.Get("/", func(c *fiber.Ctx) {
|
|||
c.Send("Hello, World!")
|
||||
})
|
||||
|
||||
//Respond to POST request on the root route (/), the application’s home page:
|
||||
app.Post("/", func(c *fiber.Ctx) {
|
||||
c.Send("Got a POST request")
|
||||
// Parameter
|
||||
// http://localhost:8080/hello%20world
|
||||
app.Post("/:value", func(c *fiber.Ctx) {
|
||||
c.Send("Post request with value: " + c.Params("value"))
|
||||
// => Post request with value: hello world
|
||||
})
|
||||
|
||||
// Respond to a PUT request to the /user route:
|
||||
app.Put("/user", func(c *fiber.Ctx) {
|
||||
c.Send("Got a PUT request at /user")
|
||||
// Optional parameter
|
||||
// http://localhost:8080/hello%20world
|
||||
app.Get("/:value?", func(c *fiber.Ctx) {
|
||||
if c.Params("value") != "" {
|
||||
c.Send("Get request with value: " + c.Params("Value"))
|
||||
return // => Post request with value: hello world
|
||||
}
|
||||
c.Send("Get request without value")
|
||||
})
|
||||
|
||||
// Respond to a DELETE request to the /user route:
|
||||
app.Delete("/user", func(c *fiber.Ctx) {
|
||||
c.Send("Got a DELETE request at /user")
|
||||
// Wildcard
|
||||
// http://localhost:8080/api/user/john
|
||||
app.Get("/api/*", func(c *fiber.Ctx) {
|
||||
c.Send("API path with wildcard: " + c.Params("*"))
|
||||
// => API path with wildcard: user/john
|
||||
})
|
||||
```
|
||||
|
||||
|
|
|
@ -19,7 +19,7 @@
|
|||
|
||||
<script>
|
||||
window.$docsify = {
|
||||
name: 'Fiber v0.9.3',
|
||||
name: 'Fiber v1.0.0-pre-release',
|
||||
repo: 'gofiber/fiber',
|
||||
loadSidebar: "sidebar.md",
|
||||
homepage: 'getting_started.md',
|
||||
|
|
|
@ -0,0 +1,106 @@
|
|||
// 🚀 Fiber, Express on Steriods
|
||||
// 📌 Don't use in production until version 1.0.0
|
||||
// 🖥 https://github.com/gofiber/fiber
|
||||
|
||||
// 🦸 Not all heroes wear capes, thank you to some amazing people
|
||||
// 💖 @valyala, @dgrr, @erikdubbelboer, @savsgio, @julienschmidt
|
||||
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"time"
|
||||
// "github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
const (
|
||||
// Version for debugging
|
||||
Version = "1.0.0-pre-release"
|
||||
// https://play.golang.org/p/r6GNeV1gbH
|
||||
banner = "" +
|
||||
" \x1b[1;32m _____ _ _\n" +
|
||||
" \x1b[1;32m| __|_| |_ ___ ___\n" +
|
||||
" \x1b[1;32m| __| | . | -_| _|\n" +
|
||||
" \x1b[1;32m|__| |_|___|___|_|\x1b[1;30m%s\x1b[1;32m%s\n" +
|
||||
" \x1b[1;30m%s\x1b[1;32m%v\x1b[0000m\n\n"
|
||||
)
|
||||
|
||||
var (
|
||||
prefork = flag.Bool("prefork", false, "use prefork")
|
||||
child = flag.Bool("child", false, "is child process")
|
||||
)
|
||||
|
||||
// Fiber structure
|
||||
type Fiber struct {
|
||||
// Server name header
|
||||
Server string
|
||||
// Disable the fiber banner on launch
|
||||
Banner bool
|
||||
// Fasthttp server settings
|
||||
Engine *engine
|
||||
// https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
|
||||
Prefork bool
|
||||
// Stores all routes
|
||||
routes []*route
|
||||
}
|
||||
|
||||
// Fasthttp settings
|
||||
// https://github.com/valyala/fasthttp/blob/master/server.go#L150
|
||||
type engine struct {
|
||||
Concurrency int
|
||||
DisableKeepAlive bool
|
||||
ReadBufferSize int
|
||||
WriteBufferSize int
|
||||
ReadTimeout time.Duration
|
||||
WriteTimeout time.Duration
|
||||
IdleTimeout time.Duration
|
||||
MaxConnsPerIP int
|
||||
MaxRequestsPerConn int
|
||||
TCPKeepalive bool
|
||||
TCPKeepalivePeriod time.Duration
|
||||
MaxRequestBodySize int
|
||||
ReduceMemoryUsage bool
|
||||
GetOnly bool
|
||||
DisableHeaderNamesNormalizing bool
|
||||
SleepWhenConcurrencyLimitsExceeded time.Duration
|
||||
NoDefaultContentType bool
|
||||
KeepHijackedConns bool
|
||||
}
|
||||
|
||||
// New creates a Fiber instance
|
||||
func New() *Fiber {
|
||||
// Parse flags
|
||||
flag.Parse()
|
||||
return &Fiber{
|
||||
// No server header is sent when set empty ""
|
||||
Server: "",
|
||||
// Fiber banner is printed by default
|
||||
// Disable if it's a child process (when preforking)
|
||||
Banner: true,
|
||||
// https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
|
||||
// Prefork can be set within code, or with flag -prefork
|
||||
Prefork: *prefork,
|
||||
// Default fasthttp settings
|
||||
// https://github.com/valyala/fasthttp/blob/master/server.go#L150
|
||||
Engine: &engine{
|
||||
Concurrency: 256 * 1024,
|
||||
DisableKeepAlive: false,
|
||||
ReadBufferSize: 4096,
|
||||
WriteBufferSize: 4096,
|
||||
WriteTimeout: 0,
|
||||
ReadTimeout: 0,
|
||||
IdleTimeout: 0,
|
||||
MaxConnsPerIP: 0,
|
||||
MaxRequestsPerConn: 0,
|
||||
TCPKeepalive: false,
|
||||
TCPKeepalivePeriod: 0,
|
||||
MaxRequestBodySize: 4 * 1024 * 1024,
|
||||
ReduceMemoryUsage: false,
|
||||
GetOnly: false,
|
||||
DisableHeaderNamesNormalizing: false,
|
||||
SleepWhenConcurrencyLimitsExceeded: 0,
|
||||
NoDefaultContentType: false,
|
||||
KeepHijackedConns: false,
|
||||
},
|
||||
}
|
||||
}
|
26
go.sum
26
go.sum
|
@ -1,5 +1,9 @@
|
|||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
|
||||
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
|
@ -11,8 +15,11 @@ github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OH
|
|||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
|
@ -20,7 +27,26 @@ github.com/valyala/fasthttp v1.8.0 h1:actnGGBYtGQmxVaZxyZpp57Vcc2NhcO7mMN0IMwCC0
|
|||
github.com/valyala/fasthttp v1.8.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w=
|
||||
github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a h1:0R4NLDRDZX6JcmhJgXi5E4b8Wg84ihbmUKp/GvSPEzc=
|
||||
github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee h1:WG0RUwxtNT4qqaXX3DPA8zHFNm/D9xaBpxzHt1WcA/E=
|
||||
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297 h1:k7pJ2yAPLPgbskkFdhRCsA77k2fySZ1zf2zCjvQCiIM=
|
||||
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/tools v0.0.0-20200119215504-eb0d8dd85bcc h1:ZA7KFRdqWZkBr0/YbHm1h08vDJ5gQdjVG/8L153z5c4=
|
||||
golang.org/x/tools v0.0.0-20200119215504-eb0d8dd85bcc/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
|
|
|
@ -0,0 +1,142 @@
|
|||
// 🚀 Fiber, Express on Steriods
|
||||
// 📌 Don't use in production until version 1.0.0
|
||||
// 🖥 https://github.com/gofiber/fiber
|
||||
|
||||
// 🦸 Not all heroes wear capes, thank you to some amazing people
|
||||
// 💖 @valyala, @dgrr, @erikdubbelboer, @savsgio, @julienschmidt
|
||||
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
// Listen : https://gofiber.github.io/fiber/#/application?id=listen
|
||||
func (r *Fiber) Listen(address interface{}, tls ...string) {
|
||||
host := ""
|
||||
switch val := address.(type) {
|
||||
case int:
|
||||
// 8080 => ":8080"
|
||||
host = ":" + strconv.Itoa(val)
|
||||
case string:
|
||||
// Address needs to contain a semicolon
|
||||
if !strings.Contains(val, ":") {
|
||||
// "8080" => ":8080"
|
||||
val = ":" + val
|
||||
}
|
||||
host = val
|
||||
default:
|
||||
panic("Host must be an INT port or STRING address")
|
||||
}
|
||||
// Copy settings to fasthttp server
|
||||
server := &fasthttp.Server{
|
||||
Handler: r.handler,
|
||||
Name: r.Server,
|
||||
Concurrency: r.Engine.Concurrency,
|
||||
DisableKeepalive: r.Engine.DisableKeepAlive,
|
||||
ReadBufferSize: r.Engine.ReadBufferSize,
|
||||
WriteBufferSize: r.Engine.WriteBufferSize,
|
||||
ReadTimeout: r.Engine.ReadTimeout,
|
||||
WriteTimeout: r.Engine.WriteTimeout,
|
||||
IdleTimeout: r.Engine.IdleTimeout,
|
||||
MaxConnsPerIP: r.Engine.MaxConnsPerIP,
|
||||
MaxRequestsPerConn: r.Engine.MaxRequestsPerConn,
|
||||
TCPKeepalive: r.Engine.TCPKeepalive,
|
||||
TCPKeepalivePeriod: r.Engine.TCPKeepalivePeriod,
|
||||
MaxRequestBodySize: r.Engine.MaxRequestBodySize,
|
||||
ReduceMemoryUsage: r.Engine.ReduceMemoryUsage,
|
||||
GetOnly: r.Engine.GetOnly,
|
||||
DisableHeaderNamesNormalizing: r.Engine.DisableHeaderNamesNormalizing,
|
||||
SleepWhenConcurrencyLimitsExceeded: r.Engine.SleepWhenConcurrencyLimitsExceeded,
|
||||
NoDefaultServerHeader: r.Server == "",
|
||||
NoDefaultContentType: r.Engine.NoDefaultContentType,
|
||||
KeepHijackedConns: r.Engine.KeepHijackedConns,
|
||||
}
|
||||
// Print banner if enabled, ignore if child proccess
|
||||
if r.Banner && !*child {
|
||||
if r.Prefork {
|
||||
fmt.Printf(banner, Version, "-prefork", "Express on steriods", host)
|
||||
} else {
|
||||
fmt.Printf(banner, Version, "", "Express on steriods", host)
|
||||
}
|
||||
}
|
||||
// Create listener
|
||||
var listener net.Listener
|
||||
var err error
|
||||
// If prefork enabled & enough cores
|
||||
if r.Prefork && runtime.NumCPU() > 1 {
|
||||
listener, err = r.reuseport(host)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
} else {
|
||||
listener, err = net.Listen("tcp4", host)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||
}
|
||||
// Check ssl files are provided
|
||||
if len(tls) > 1 {
|
||||
if err := server.ServeTLS(listener, tls[0], tls[1]); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
if err := server.Serve(listener); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: enable ipv6 support ~ tcp4 > tcp = tcp4+tcp6
|
||||
// https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
|
||||
func (r *Fiber) reuseport(host string) (net.Listener, error) {
|
||||
var listener net.Listener
|
||||
if !*child {
|
||||
addr, err := net.ResolveTCPAddr("tcp4", host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tcplistener, err := net.ListenTCP("tcp4", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
file, err := tcplistener.File()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
childs := make([]*exec.Cmd, runtime.NumCPU())
|
||||
for i := range childs {
|
||||
childs[i] = exec.Command(os.Args[0], append(os.Args[1:], "-child")...)
|
||||
childs[i].Stdout = os.Stdout
|
||||
childs[i].Stderr = os.Stderr
|
||||
childs[i].ExtraFiles = []*os.File{file}
|
||||
if err := childs[i].Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, child := range childs {
|
||||
if err := child.Wait(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
os.Exit(0)
|
||||
panic("Problem with calling os.Exit(0)")
|
||||
} else {
|
||||
// fmt.Printf(" \x1b[1;30mChild \x1b[1;32m#%v\x1b[1;30m reuseport\x1b[1;32m%s\x1b[0000m\n", os.Getpid(), host)
|
||||
var err error
|
||||
listener, err = net.FileListener(os.NewFile(3, ""))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
runtime.GOMAXPROCS(1)
|
||||
}
|
||||
return listener, nil
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
// 🚀 Fiber, Express on Steriods
|
||||
// 📌 Don't use in production until version 1.0.0
|
||||
// 🖥 https://github.com/gofiber/fiber
|
||||
|
||||
// 🦸 Not all heroes wear capes, thank you to some amazing people
|
||||
// 💖 @valyala, @dgrr, @erikdubbelboer, @savsgio, @julienschmidt
|
||||
|
||||
package fiber
|
||||
|
||||
// Connect establishes a tunnel to the server
|
||||
// identified by the target resource.
|
||||
func (r *Fiber) Connect(args ...interface{}) {
|
||||
r.register("CONNECT", args...)
|
||||
}
|
||||
|
||||
// Put replaces all current representations
|
||||
// of the target resource with the request payload.
|
||||
func (r *Fiber) Put(args ...interface{}) {
|
||||
r.register("PUT", args...)
|
||||
}
|
||||
|
||||
// Post is used to submit an entity to the specified resource,
|
||||
// often causing a change in state or side effects on the server.
|
||||
func (r *Fiber) Post(args ...interface{}) {
|
||||
r.register("POST", args...)
|
||||
}
|
||||
|
||||
// Delete deletes the specified resource.
|
||||
func (r *Fiber) Delete(args ...interface{}) {
|
||||
r.register("DELETE", args...)
|
||||
}
|
||||
|
||||
// Head asks for a response identical to that of a GET request,
|
||||
// but without the response body.
|
||||
func (r *Fiber) Head(args ...interface{}) {
|
||||
r.register("HEAD", args...)
|
||||
}
|
||||
|
||||
// Patch is used to apply partial modifications to a resource.
|
||||
func (r *Fiber) Patch(args ...interface{}) {
|
||||
r.register("PATCH", args...)
|
||||
}
|
||||
|
||||
// Options is used to describe the communication options
|
||||
// for the target resource.
|
||||
func (r *Fiber) Options(args ...interface{}) {
|
||||
r.register("OPTIONS", args...)
|
||||
}
|
||||
|
||||
// Trace performs a message loop-back test
|
||||
// along the path to the target resource.
|
||||
func (r *Fiber) Trace(args ...interface{}) {
|
||||
r.register("TRACE", args...)
|
||||
}
|
||||
|
||||
// Get requests a representation of the specified resource.
|
||||
// Requests using GET should only retrieve data.
|
||||
func (r *Fiber) Get(args ...interface{}) {
|
||||
r.register("GET", args...)
|
||||
}
|
||||
|
||||
// All matches any HTTP method
|
||||
func (r *Fiber) All(args ...interface{}) {
|
||||
r.register("*", args...)
|
||||
}
|
||||
|
||||
// Use is another name for All()
|
||||
// People using Expressjs are used to this
|
||||
func (r *Fiber) Use(args ...interface{}) {
|
||||
r.All(args...)
|
||||
}
|
|
@ -0,0 +1,286 @@
|
|||
// 🚀 Fiber, Express on Steriods
|
||||
// 📌 Don't use in production until version 1.0.0
|
||||
// 🖥 https://github.com/gofiber/fiber
|
||||
|
||||
// 🦸 Not all heroes wear capes, thank you to some amazing people
|
||||
// 💖 @valyala, @dgrr, @erikdubbelboer, @savsgio, @julienschmidt
|
||||
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Accepts : https://gofiber.github.io/fiber/#/context?id=accepts
|
||||
func (ctx *Ctx) Accepts(typ string) bool {
|
||||
accept := ctx.Get("Accept-Charset")
|
||||
if strings.Contains(accept, typ) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AcceptsCharsets : https://gofiber.github.io/fiber/#/context?id=acceptscharsets
|
||||
func (ctx *Ctx) AcceptsCharsets(charset string) bool {
|
||||
accept := ctx.Get("Accept-Charset")
|
||||
if strings.Contains(accept, charset) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AcceptsEncodings : https://gofiber.github.io/fiber/#/context?id=acceptsencodings
|
||||
func (ctx *Ctx) AcceptsEncodings(encoding string) bool {
|
||||
accept := ctx.Get("Accept-Encoding")
|
||||
if strings.Contains(accept, encoding) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AcceptsLanguages : https://gofiber.github.io/fiber/#/context?id=acceptslanguages
|
||||
func (ctx *Ctx) AcceptsLanguages(lang string) bool {
|
||||
accept := ctx.Get("Accept-Language")
|
||||
if strings.Contains(accept, lang) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// BaseUrl : https://gofiber.github.io/fiber/#/context?id=baseurl
|
||||
func (ctx *Ctx) BaseUrl() string {
|
||||
return ctx.Protocol() + "://" + ctx.Hostname()
|
||||
}
|
||||
|
||||
// BasicAuth : https://gofiber.github.io/fiber/#/context?id=basicauth
|
||||
func (ctx *Ctx) BasicAuth() (user, pass string, ok bool) {
|
||||
auth := ctx.Get("Authorization")
|
||||
if auth == "" {
|
||||
return
|
||||
}
|
||||
const prefix = "Basic "
|
||||
// Case insensitive prefix match.
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return
|
||||
}
|
||||
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cs := b2s(c)
|
||||
s := strings.IndexByte(cs, ':')
|
||||
if s < 0 {
|
||||
return
|
||||
}
|
||||
return cs[:s], cs[s+1:], true
|
||||
}
|
||||
|
||||
// Body : https://gofiber.github.io/fiber/#/context?id=body
|
||||
func (ctx *Ctx) Body(args ...interface{}) string {
|
||||
if len(args) == 0 {
|
||||
return b2s(ctx.Fasthttp.Request.Body())
|
||||
}
|
||||
if len(args) == 1 {
|
||||
switch arg := args[0].(type) {
|
||||
case string:
|
||||
return b2s(ctx.Fasthttp.Request.PostArgs().Peek(arg))
|
||||
case func(string, string):
|
||||
ctx.Fasthttp.Request.PostArgs().VisitAll(func(k []byte, v []byte) {
|
||||
arg(b2s(k), b2s(v))
|
||||
})
|
||||
default:
|
||||
return b2s(ctx.Fasthttp.Request.Body())
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Cookies : https://gofiber.github.io/fiber/#/context?id=cookies
|
||||
func (ctx *Ctx) Cookies(args ...interface{}) string {
|
||||
if len(args) == 0 {
|
||||
//return b2s(ctx.Fasthttp.Response.Header.Peek("Cookie"))
|
||||
return ctx.Get("Cookie")
|
||||
}
|
||||
switch arg := args[0].(type) {
|
||||
case string:
|
||||
return b2s(ctx.Fasthttp.Request.Header.Cookie(arg))
|
||||
case func(string, string):
|
||||
ctx.Fasthttp.Request.Header.VisitAllCookie(func(k, v []byte) {
|
||||
arg(b2s(k), b2s(v))
|
||||
})
|
||||
default:
|
||||
panic("Argument must be a string or func(string, string)")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// FormFile : https://gofiber.github.io/fiber/#/context?id=formfile
|
||||
func (ctx *Ctx) FormFile(key string) (*multipart.FileHeader, error) {
|
||||
return ctx.Fasthttp.FormFile(key)
|
||||
}
|
||||
|
||||
// FormValue : https://gofiber.github.io/fiber/#/context?id=formvalue
|
||||
func (ctx *Ctx) FormValue(key string) string {
|
||||
return b2s(ctx.Fasthttp.FormValue(key))
|
||||
}
|
||||
|
||||
// Fresh : https://gofiber.github.io/fiber/#/context?id=fresh
|
||||
func (ctx *Ctx) Fresh() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Get : https://gofiber.github.io/fiber/#/context?id=get
|
||||
func (ctx *Ctx) Get(key string) string {
|
||||
// https://en.wikipedia.org/wiki/HTTP_referer
|
||||
if key == "referrer" {
|
||||
key = "referer"
|
||||
}
|
||||
return b2s(ctx.Fasthttp.Request.Header.Peek(key))
|
||||
}
|
||||
|
||||
// Hostname : https://gofiber.github.io/fiber/#/context?id=hostname
|
||||
func (ctx *Ctx) Hostname() string {
|
||||
return b2s(ctx.Fasthttp.URI().Host())
|
||||
}
|
||||
|
||||
// Ip : https://gofiber.github.io/fiber/#/context?id=Ip
|
||||
func (ctx *Ctx) Ip() string {
|
||||
return ctx.Fasthttp.RemoteIP().String()
|
||||
}
|
||||
|
||||
// Ips : https://gofiber.github.io/fiber/#/context?id=ips
|
||||
func (ctx *Ctx) Ips() []string {
|
||||
ips := strings.Split(ctx.Get("X-Forwarded-For"), ",")
|
||||
for i := range ips {
|
||||
ips[i] = strings.TrimSpace(ips[i])
|
||||
}
|
||||
return ips
|
||||
}
|
||||
|
||||
// Is : https://gofiber.github.io/fiber/#/context?id=is
|
||||
func (ctx *Ctx) Is(ext string) bool {
|
||||
if ext[0] != '.' {
|
||||
ext = "." + ext
|
||||
}
|
||||
exts, _ := mime.ExtensionsByType(ctx.Get("Content-Type"))
|
||||
if len(exts) > 0 {
|
||||
for _, item := range exts {
|
||||
if item == ext {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Locals : https://gofiber.github.io/fiber/#/context?id=locals
|
||||
func (ctx *Ctx) Locals(key string, val ...interface{}) interface{} {
|
||||
if len(val) == 0 {
|
||||
return ctx.Fasthttp.UserValue(key)
|
||||
} else {
|
||||
ctx.Fasthttp.SetUserValue(key, val[0])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Method : https://gofiber.github.io/fiber/#/context?id=method
|
||||
func (ctx *Ctx) Method() string {
|
||||
return b2s(ctx.Fasthttp.Request.Header.Method())
|
||||
}
|
||||
|
||||
// MultipartForm : https://gofiber.github.io/fiber/#/context?id=multipartform
|
||||
func (ctx *Ctx) MultipartForm() (*multipart.Form, error) {
|
||||
return ctx.Fasthttp.MultipartForm()
|
||||
}
|
||||
|
||||
// OriginalUrl : https://gofiber.github.io/fiber/#/context?id=originalurl
|
||||
func (ctx *Ctx) OriginalUrl() string {
|
||||
return b2s(ctx.Fasthttp.Request.Header.RequestURI())
|
||||
}
|
||||
|
||||
// Params : https://gofiber.github.io/fiber/#/context?id=params
|
||||
func (ctx *Ctx) Params(key string) string {
|
||||
if ctx.params == nil {
|
||||
return ""
|
||||
}
|
||||
for i := 0; i < len(*ctx.params); i++ {
|
||||
if (*ctx.params)[i] == key {
|
||||
return ctx.values[i]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Path : https://gofiber.github.io/fiber/#/context?id=path
|
||||
func (ctx *Ctx) Path() string {
|
||||
return b2s(ctx.Fasthttp.URI().Path())
|
||||
}
|
||||
|
||||
// Protocol : https://gofiber.github.io/fiber/#/context?id=protocol
|
||||
func (ctx *Ctx) Protocol() string {
|
||||
if ctx.Fasthttp.IsTLS() {
|
||||
return "https"
|
||||
}
|
||||
return "http"
|
||||
}
|
||||
|
||||
// Query : https://gofiber.github.io/fiber/#/context?id=query
|
||||
func (ctx *Ctx) Query(key string) string {
|
||||
return b2s(ctx.Fasthttp.QueryArgs().Peek(key))
|
||||
}
|
||||
|
||||
// Range : https://gofiber.github.io/fiber/#/context?id=range
|
||||
func (ctx *Ctx) Range() {
|
||||
|
||||
}
|
||||
|
||||
// Route : https://gofiber.github.io/fiber/#/context?id=route
|
||||
func (ctx *Ctx) Route() (s struct {
|
||||
Method string
|
||||
Path string
|
||||
Wildcard bool
|
||||
Regex *regexp.Regexp
|
||||
Params []string
|
||||
Values []string
|
||||
Handler func(*Ctx)
|
||||
}) {
|
||||
s.Method = ctx.route.method
|
||||
s.Path = ctx.route.path
|
||||
s.Wildcard = ctx.route.wildcard
|
||||
s.Regex = ctx.route.regex
|
||||
s.Params = ctx.route.params
|
||||
s.Values = ctx.values
|
||||
s.Handler = ctx.route.handler
|
||||
return
|
||||
}
|
||||
|
||||
// Secure : https://gofiber.github.io/fiber/#/context?id=secure
|
||||
func (ctx *Ctx) Secure() bool {
|
||||
return ctx.Fasthttp.IsTLS()
|
||||
}
|
||||
|
||||
// SignedCookies : https://gofiber.github.io/fiber/#/context?id=signedcookies
|
||||
func (ctx *Ctx) SignedCookies() {
|
||||
|
||||
}
|
||||
|
||||
// Stale : https://gofiber.github.io/fiber/#/context?id=stale
|
||||
func (ctx *Ctx) Stale() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Subdomains : https://gofiber.github.io/fiber/#/context?id=subdomains
|
||||
func (ctx *Ctx) Subdomains() (subs []string) {
|
||||
subs = strings.Split(ctx.Hostname(), ".")
|
||||
subs = subs[:len(subs)-2]
|
||||
return subs
|
||||
}
|
||||
|
||||
// Xhr : https://gofiber.github.io/fiber/#/context?id=xhr
|
||||
func (ctx *Ctx) Xhr() bool {
|
||||
return ctx.Get("X-Requested-With") == "XMLHttpRequest"
|
||||
}
|
|
@ -0,0 +1,305 @@
|
|||
// 🚀 Fiber, Express on Steriods
|
||||
// 📌 Don't use in production until version 1.0.0
|
||||
// 🖥 https://github.com/gofiber/fiber
|
||||
|
||||
// 🦸 Not all heroes wear capes, thank you to some amazing people
|
||||
// 💖 @valyala, @dgrr, @erikdubbelboer, @savsgio, @julienschmidt
|
||||
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"mime"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
// Append : https://gofiber.github.io/fiber/#/context?id=append
|
||||
func (ctx *Ctx) Append(field string, values ...string) {
|
||||
newVal := ctx.Get(field)
|
||||
if len(values) > 0 {
|
||||
for i := range values {
|
||||
newVal = newVal + ", " + values[i]
|
||||
}
|
||||
}
|
||||
ctx.Set(field, newVal)
|
||||
}
|
||||
|
||||
// Attachment : https://gofiber.github.io/fiber/#/context?id=attachment
|
||||
func (ctx *Ctx) Attachment(name ...string) {
|
||||
if len(name) > 0 {
|
||||
filename := filepath.Base(name[0])
|
||||
ctx.Type(filepath.Ext(filename))
|
||||
ctx.Set("Content-Disposition", `attachment; filename="`+filename+`"`)
|
||||
return
|
||||
}
|
||||
ctx.Set("Content-Disposition", "attachment")
|
||||
}
|
||||
|
||||
// ClearCookie : https://gofiber.github.io/fiber/#/context?id=clearcookie
|
||||
func (ctx *Ctx) ClearCookie(name ...string) {
|
||||
if len(name) == 0 {
|
||||
ctx.Fasthttp.Request.Header.VisitAllCookie(func(k, v []byte) {
|
||||
fmt.Println(b2s(k), b2s(v))
|
||||
ctx.Fasthttp.Response.Header.DelClientCookie(b2s(k))
|
||||
})
|
||||
} else if len(name) > 0 {
|
||||
for i := range name {
|
||||
ctx.Fasthttp.Response.Header.DelClientCookie(name[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cookie : https://gofiber.github.io/fiber/#/context?id=cookie
|
||||
func (ctx *Ctx) Cookie(key, value string, options ...interface{}) {
|
||||
cook := &fasthttp.Cookie{}
|
||||
cook.SetKey(key)
|
||||
cook.SetValue(value)
|
||||
if len(options) > 0 {
|
||||
switch opt := options[0].(type) {
|
||||
case *Cookie:
|
||||
if opt.Expire > 0 {
|
||||
cook.SetExpire(time.Unix(int64(opt.Expire), 0))
|
||||
}
|
||||
if opt.MaxAge > 0 {
|
||||
cook.SetMaxAge(opt.MaxAge)
|
||||
}
|
||||
if opt.Domain != "" {
|
||||
cook.SetDomain(opt.Domain)
|
||||
}
|
||||
if opt.Path != "" {
|
||||
cook.SetPath(opt.Path)
|
||||
}
|
||||
if opt.HttpOnly {
|
||||
cook.SetHTTPOnly(opt.HttpOnly)
|
||||
}
|
||||
if opt.Secure {
|
||||
cook.SetSecure(opt.Secure)
|
||||
}
|
||||
if opt.SameSite != "" {
|
||||
sameSite := fasthttp.CookieSameSiteDisabled
|
||||
if strings.EqualFold(opt.SameSite, "lax") {
|
||||
sameSite = fasthttp.CookieSameSiteLaxMode
|
||||
} else if strings.EqualFold(opt.SameSite, "strict") {
|
||||
sameSite = fasthttp.CookieSameSiteStrictMode
|
||||
} else if strings.EqualFold(opt.SameSite, "none") {
|
||||
sameSite = fasthttp.CookieSameSiteNoneMode
|
||||
} else {
|
||||
sameSite = fasthttp.CookieSameSiteDefaultMode
|
||||
}
|
||||
cook.SetSameSite(sameSite)
|
||||
}
|
||||
default:
|
||||
panic("Invalid cookie options")
|
||||
}
|
||||
}
|
||||
ctx.Fasthttp.Response.Header.SetCookie(cook)
|
||||
}
|
||||
|
||||
// Download : https://gofiber.github.io/fiber/#/context?id=download
|
||||
func (ctx *Ctx) Download(file string, name ...string) {
|
||||
filename := filepath.Base(file)
|
||||
if len(name) > 0 {
|
||||
filename = name[0]
|
||||
}
|
||||
ctx.Set("Content-Disposition", "attachment; filename="+filename)
|
||||
ctx.SendFile(file)
|
||||
}
|
||||
|
||||
// End : https://gofiber.github.io/fiber/#/context?id=end
|
||||
func (ctx *Ctx) End() {
|
||||
|
||||
}
|
||||
|
||||
// Format : https://gofiber.github.io/fiber/#/context?id=format
|
||||
func (ctx *Ctx) Format() {
|
||||
|
||||
}
|
||||
|
||||
// HeadersSent : https://gofiber.github.io/fiber/#/context?id=headerssent
|
||||
func (ctx *Ctx) HeadersSent() {
|
||||
|
||||
}
|
||||
|
||||
// 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.Set("Content-Type", "application/json")
|
||||
ctx.Fasthttp.Response.SetBodyString(b2s(raw))
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
if len(cb) > 0 {
|
||||
builder.Write(s2b(cb[0]))
|
||||
} else {
|
||||
builder.Write([]byte("callback"))
|
||||
}
|
||||
builder.Write([]byte("("))
|
||||
builder.Write(raw)
|
||||
builder.Write([]byte(");"))
|
||||
|
||||
ctx.Set("X-Content-Type-Options", "nosniff")
|
||||
ctx.Set("Content-Type", "application/javascript")
|
||||
ctx.Fasthttp.Response.SetBodyString(builder.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
// Links : https://gofiber.github.io/fiber/#/context?id=links
|
||||
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, ",")
|
||||
ctx.Set("Link", h)
|
||||
}
|
||||
}
|
||||
|
||||
// Location : https://gofiber.github.io/fiber/#/context?id=location
|
||||
func (ctx *Ctx) Location(path string) {
|
||||
ctx.Set("Location", path)
|
||||
}
|
||||
|
||||
// Next : https://gofiber.github.io/fiber/#/context?id=next
|
||||
func (ctx *Ctx) Next() {
|
||||
ctx.next = true
|
||||
ctx.params = nil
|
||||
ctx.values = nil
|
||||
}
|
||||
|
||||
// Redirect : https://gofiber.github.io/fiber/#/context?id=redirect
|
||||
func (ctx *Ctx) Redirect(path string, status ...int) {
|
||||
ctx.Set("Location", path)
|
||||
if len(status) > 0 {
|
||||
ctx.Status(status[0])
|
||||
} else {
|
||||
ctx.Status(302)
|
||||
}
|
||||
}
|
||||
|
||||
// Render : https://gofiber.github.io/fiber/#/context?id=render
|
||||
func (ctx *Ctx) Render() {
|
||||
|
||||
}
|
||||
|
||||
// Send : https://gofiber.github.io/fiber/#/context?id=send
|
||||
func (ctx *Ctx) Send(args ...interface{}) {
|
||||
|
||||
// https://github.com/valyala/fasthttp/blob/master/http.go#L490
|
||||
if len(args) != 1 {
|
||||
panic("To many arguments!")
|
||||
}
|
||||
switch body := args[0].(type) {
|
||||
case string:
|
||||
//ctx.Fasthttp.Response.SetBodyRaw(s2b(body))
|
||||
ctx.Fasthttp.Response.SetBodyString(body)
|
||||
case []byte:
|
||||
//ctx.Fasthttp.Response.SetBodyRaw(body)
|
||||
ctx.Fasthttp.Response.SetBodyString(b2s(body))
|
||||
default:
|
||||
panic("body must be a string or []byte")
|
||||
}
|
||||
}
|
||||
|
||||
// SendBytes : https://gofiber.github.io/fiber/#/context?id=sendbytes
|
||||
func (ctx *Ctx) SendBytes(body []byte) {
|
||||
ctx.Fasthttp.Response.SetBodyString(b2s(body))
|
||||
}
|
||||
|
||||
// SendFile : https://gofiber.github.io/fiber/#/context?id=sendfile
|
||||
func (ctx *Ctx) SendFile(file string, gzip ...bool) {
|
||||
// Disable gzipping
|
||||
if len(gzip) > 0 && !gzip[0] {
|
||||
fasthttp.ServeFileUncompressed(ctx.Fasthttp, file)
|
||||
}
|
||||
fasthttp.ServeFile(ctx.Fasthttp, file)
|
||||
// https://github.com/valyala/fasthttp/blob/master/fs.go#L81
|
||||
//ctx.Type(filepath.Ext(path))
|
||||
//ctx.Fasthttp.SendFile(path)
|
||||
}
|
||||
|
||||
// SendStatus : https://gofiber.github.io/fiber/#/context?id=sendstatus
|
||||
func (ctx *Ctx) SendStatus(status int) {
|
||||
ctx.Status(status)
|
||||
// Only set status body when there is no response body
|
||||
if len(ctx.Fasthttp.Response.Body()) == 0 {
|
||||
msg := statusMessages[status]
|
||||
if msg != "" {
|
||||
ctx.Fasthttp.Response.SetBodyString(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SendString : https://gofiber.github.io/fiber/#/context?id=sendstring
|
||||
func (ctx *Ctx) SendString(body string) {
|
||||
ctx.Fasthttp.Response.SetBodyString(body)
|
||||
}
|
||||
|
||||
// Set : https://gofiber.github.io/fiber/#/context?id=set
|
||||
func (ctx *Ctx) Set(key string, val string) {
|
||||
ctx.Fasthttp.Response.Header.SetCanonical(s2b(key), s2b(val))
|
||||
}
|
||||
|
||||
// Status : https://gofiber.github.io/fiber/#/context?id=status
|
||||
func (ctx *Ctx) Status(status int) *Ctx {
|
||||
ctx.Fasthttp.Response.SetStatusCode(status)
|
||||
return ctx
|
||||
}
|
||||
|
||||
// Type : https://gofiber.github.io/fiber/#/context?id=type
|
||||
func (ctx *Ctx) Type(ext string) *Ctx {
|
||||
if ext[0] != '.' {
|
||||
ext = "." + ext
|
||||
}
|
||||
m := mime.TypeByExtension(ext)
|
||||
ctx.Set("Content-Type", m)
|
||||
return ctx
|
||||
}
|
||||
|
||||
// Vary : https://gofiber.github.io/fiber/#/context?id=vary
|
||||
func (ctx *Ctx) Vary(field ...string) {
|
||||
vary := ctx.Get("Vary")
|
||||
for _, f := range field {
|
||||
if !strings.Contains(vary, f) {
|
||||
vary += ", " + f
|
||||
}
|
||||
}
|
||||
if len(field) > 0 {
|
||||
ctx.Set("Vary", vary)
|
||||
}
|
||||
}
|
||||
|
||||
// Write : https://gofiber.github.io/fiber/#/context?id=write
|
||||
func (ctx *Ctx) Write(args ...interface{}) {
|
||||
if len(args) == 0 {
|
||||
panic("Missing body")
|
||||
}
|
||||
switch body := args[0].(type) {
|
||||
case string:
|
||||
ctx.Fasthttp.Response.SetBodyString(body)
|
||||
case []byte:
|
||||
ctx.Fasthttp.Response.AppendBodyString(b2s(body))
|
||||
default:
|
||||
panic("body must be a string or []byte")
|
||||
}
|
||||
}
|
335
router.go
335
router.go
|
@ -8,59 +8,11 @@
|
|||
package fiber
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
// "github.com/tidwall/gjson"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
const (
|
||||
// Version for debugging
|
||||
Version = "0.9.3"
|
||||
// https://play.golang.org/p/r6GNeV1gbH
|
||||
banner = "" +
|
||||
" \x1b[1;32m _____ _ _\n" +
|
||||
" \x1b[1;32m| __|_| |_ ___ ___\n" +
|
||||
" \x1b[1;32m| __| | . | -_| _|\n" +
|
||||
" \x1b[1;32m|__| |_|___|___|_|\x1b[1;30m%s\x1b[1;32m%s\n" +
|
||||
" \x1b[1;30m%s\x1b[1;32m%v\x1b[0000m\n\n"
|
||||
)
|
||||
|
||||
var (
|
||||
prefork = flag.Bool("prefork", false, "use prefork")
|
||||
child = flag.Bool("child", false, "is child process")
|
||||
)
|
||||
|
||||
// Fiber structure
|
||||
type Fiber struct {
|
||||
// Stores all routes
|
||||
routes []*route
|
||||
// Server name header
|
||||
Server string
|
||||
// Disable the fiber banner on launch
|
||||
Banner bool
|
||||
// Provide certificate files to enable TLS
|
||||
CertKey string
|
||||
CertFile string
|
||||
// Fasthttp server settings
|
||||
Fasthttp *Fasthttp
|
||||
// https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
|
||||
// -prefork
|
||||
Prefork bool
|
||||
// -child
|
||||
Child bool
|
||||
}
|
||||
|
||||
type route struct {
|
||||
// HTTP method in uppercase, can be a * for Use() & All()
|
||||
method string
|
||||
|
@ -76,185 +28,6 @@ type route struct {
|
|||
handler func(*Ctx)
|
||||
}
|
||||
|
||||
// Fasthttp settings
|
||||
// https://github.com/valyala/fasthttp/blob/master/server.go#L150
|
||||
type Fasthttp struct {
|
||||
Concurrency int
|
||||
DisableKeepAlive bool
|
||||
ReadBufferSize int
|
||||
WriteBufferSize int
|
||||
ReadTimeout time.Duration
|
||||
WriteTimeout time.Duration
|
||||
IdleTimeout time.Duration
|
||||
MaxConnsPerIP int
|
||||
MaxRequestsPerConn int
|
||||
TCPKeepalive bool
|
||||
TCPKeepalivePeriod time.Duration
|
||||
MaxRequestBodySize int
|
||||
ReduceMemoryUsage bool
|
||||
GetOnly bool
|
||||
DisableHeaderNamesNormalizing bool
|
||||
SleepWhenConcurrencyLimitsExceeded time.Duration
|
||||
NoDefaultContentType bool
|
||||
KeepHijackedConns bool
|
||||
}
|
||||
|
||||
// New creates a Fiber instance
|
||||
func New() *Fiber {
|
||||
// Parse flags
|
||||
flag.Parse()
|
||||
return &Fiber{
|
||||
// No server header is sent when set empty ""
|
||||
Server: "",
|
||||
// TLS is disabled by default, unless files are provided
|
||||
CertKey: "",
|
||||
CertFile: "",
|
||||
// Fiber banner is printed by default
|
||||
// Disable if it's a child process (when preforking)
|
||||
Banner: true,
|
||||
// https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
|
||||
// Prefork can be set within code, or with flag -prefork
|
||||
Prefork: *prefork,
|
||||
// True or false if process is child when prefork is enabled
|
||||
Child: *child,
|
||||
// Default fasthttp settings
|
||||
// https://github.com/valyala/fasthttp/blob/master/server.go#L150
|
||||
Fasthttp: &Fasthttp{
|
||||
Concurrency: 256 * 1024,
|
||||
DisableKeepAlive: false,
|
||||
ReadBufferSize: 4096,
|
||||
WriteBufferSize: 4096,
|
||||
WriteTimeout: 0,
|
||||
ReadTimeout: 0,
|
||||
IdleTimeout: 0,
|
||||
MaxConnsPerIP: 0,
|
||||
MaxRequestsPerConn: 0,
|
||||
TCPKeepalive: false,
|
||||
TCPKeepalivePeriod: 0,
|
||||
MaxRequestBodySize: 4 * 1024 * 1024,
|
||||
ReduceMemoryUsage: false,
|
||||
GetOnly: false,
|
||||
DisableHeaderNamesNormalizing: false,
|
||||
SleepWhenConcurrencyLimitsExceeded: 0,
|
||||
NoDefaultContentType: false,
|
||||
KeepHijackedConns: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Connect establishes a tunnel to the server
|
||||
// identified by the target resource.
|
||||
func (r *Fiber) Connect(args ...interface{}) {
|
||||
r.register("CONNECT", args...)
|
||||
}
|
||||
|
||||
// Put replaces all current representations
|
||||
// of the target resource with the request payload.
|
||||
func (r *Fiber) Put(args ...interface{}) {
|
||||
r.register("PUT", args...)
|
||||
}
|
||||
|
||||
// Post is used to submit an entity to the specified resource,
|
||||
// often causing a change in state or side effects on the server.
|
||||
func (r *Fiber) Post(args ...interface{}) {
|
||||
r.register("POST", args...)
|
||||
}
|
||||
|
||||
// Delete deletes the specified resource.
|
||||
func (r *Fiber) Delete(args ...interface{}) {
|
||||
r.register("DELETE", args...)
|
||||
}
|
||||
|
||||
// Head asks for a response identical to that of a GET request,
|
||||
// but without the response body.
|
||||
func (r *Fiber) Head(args ...interface{}) {
|
||||
r.register("HEAD", args...)
|
||||
}
|
||||
|
||||
// Patch is used to apply partial modifications to a resource.
|
||||
func (r *Fiber) Patch(args ...interface{}) {
|
||||
r.register("PATCH", args...)
|
||||
}
|
||||
|
||||
// Options is used to describe the communication options
|
||||
// for the target resource.
|
||||
func (r *Fiber) Options(args ...interface{}) {
|
||||
r.register("OPTIONS", args...)
|
||||
}
|
||||
|
||||
// Trace performs a message loop-back test
|
||||
// along the path to the target resource.
|
||||
func (r *Fiber) Trace(args ...interface{}) {
|
||||
r.register("TRACE", args...)
|
||||
}
|
||||
|
||||
// Get requests a representation of the specified resource.
|
||||
// Requests using GET should only retrieve data.
|
||||
func (r *Fiber) Get(args ...interface{}) {
|
||||
r.register("GET", args...)
|
||||
}
|
||||
|
||||
// All matches any HTTP method
|
||||
func (r *Fiber) All(args ...interface{}) {
|
||||
r.register("*", args...)
|
||||
}
|
||||
|
||||
// Use is another name for All()
|
||||
// People using Expressjs are used to this
|
||||
func (r *Fiber) Use(args ...interface{}) {
|
||||
r.All(args...)
|
||||
}
|
||||
|
||||
// Static :
|
||||
func (r *Fiber) Static(args ...string) {
|
||||
prefix := "/"
|
||||
root := "./"
|
||||
wildcard := false
|
||||
gzip := true
|
||||
if len(args) == 1 {
|
||||
root = args[0]
|
||||
} else if len(args) == 2 {
|
||||
prefix = args[0]
|
||||
root = args[1]
|
||||
if prefix[0] != '/' {
|
||||
prefix = "/" + prefix
|
||||
}
|
||||
}
|
||||
// Check if wildcard for single files
|
||||
if prefix == "*" || prefix == "/*" {
|
||||
wildcard = true
|
||||
}
|
||||
// Lets get all files from root
|
||||
files, _, err := walkDir(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" {
|
||||
r.routes = append(r.routes, &route{"GET", prefix, wildcard, 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, nil, nil, func(c *Ctx) {
|
||||
c.SendFile(filePath, gzip)
|
||||
}})
|
||||
}
|
||||
}
|
||||
|
||||
// Function to add a route correctly
|
||||
func (r *Fiber) register(method string, args ...interface{}) {
|
||||
// Prepare possible variables
|
||||
|
@ -292,7 +65,6 @@ func (r *Fiber) register(method string, args ...interface{}) {
|
|||
r.routes = append(r.routes, &route{method, path, false, regex, params, handler})
|
||||
}
|
||||
|
||||
// handler create a new context struct from the pool
|
||||
// then try to match a route as efficient as possible.
|
||||
func (r *Fiber) handler(fctx *fasthttp.RequestCtx) {
|
||||
found := false
|
||||
|
@ -365,110 +137,3 @@ func (r *Fiber) handler(fctx *fasthttp.RequestCtx) {
|
|||
// release context back into sync pool
|
||||
releaseCtx(ctx)
|
||||
}
|
||||
|
||||
// Listen starts the server with the correct settings
|
||||
func (r *Fiber) Listen(port int, addr ...string) {
|
||||
host := fmt.Sprintf(":%v", port)
|
||||
if len(addr) > 0 {
|
||||
host = fmt.Sprintf("%s:%v", addr[0], port)
|
||||
}
|
||||
// Copy settings to fasthttp server
|
||||
server := &fasthttp.Server{
|
||||
Handler: r.handler,
|
||||
Name: r.Server,
|
||||
Concurrency: r.Fasthttp.Concurrency,
|
||||
DisableKeepalive: r.Fasthttp.DisableKeepAlive,
|
||||
ReadBufferSize: r.Fasthttp.ReadBufferSize,
|
||||
WriteBufferSize: r.Fasthttp.WriteBufferSize,
|
||||
ReadTimeout: r.Fasthttp.ReadTimeout,
|
||||
WriteTimeout: r.Fasthttp.WriteTimeout,
|
||||
IdleTimeout: r.Fasthttp.IdleTimeout,
|
||||
MaxConnsPerIP: r.Fasthttp.MaxConnsPerIP,
|
||||
MaxRequestsPerConn: r.Fasthttp.MaxRequestsPerConn,
|
||||
TCPKeepalive: r.Fasthttp.TCPKeepalive,
|
||||
TCPKeepalivePeriod: r.Fasthttp.TCPKeepalivePeriod,
|
||||
MaxRequestBodySize: r.Fasthttp.MaxRequestBodySize,
|
||||
ReduceMemoryUsage: r.Fasthttp.ReduceMemoryUsage,
|
||||
GetOnly: r.Fasthttp.GetOnly,
|
||||
DisableHeaderNamesNormalizing: r.Fasthttp.DisableHeaderNamesNormalizing,
|
||||
SleepWhenConcurrencyLimitsExceeded: r.Fasthttp.SleepWhenConcurrencyLimitsExceeded,
|
||||
NoDefaultServerHeader: r.Server == "",
|
||||
NoDefaultContentType: r.Fasthttp.NoDefaultContentType,
|
||||
KeepHijackedConns: r.Fasthttp.KeepHijackedConns,
|
||||
}
|
||||
// Print banner if enabled
|
||||
if r.Banner && !r.Child {
|
||||
if r.Prefork {
|
||||
fmt.Printf(banner, Version, "-prefork", "Express on steriods", host)
|
||||
} else {
|
||||
fmt.Printf(banner, Version, "", "Express on steriods", host)
|
||||
}
|
||||
}
|
||||
// Create listener
|
||||
var listener net.Listener
|
||||
var err error
|
||||
if r.Prefork {
|
||||
listener, err = r.reuseport(host)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
} else {
|
||||
listener, err = net.Listen("tcp4", host)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||
}
|
||||
// Check if TLS is enabled
|
||||
if r.CertKey != "" && r.CertFile != "" {
|
||||
if err := server.ServeTLS(listener, r.CertFile, r.CertKey); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
if err := server.Serve(listener); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Fiber) reuseport(host string) (net.Listener, error) {
|
||||
var listener net.Listener
|
||||
if !r.Child {
|
||||
addr, err := net.ResolveTCPAddr("tcp4", host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tcplistener, err := net.ListenTCP("tcp4", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fl, err := tcplistener.File()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
children := make([]*exec.Cmd, runtime.NumCPU())
|
||||
for i := range children {
|
||||
children[i] = exec.Command(os.Args[0], append(os.Args[1:], "-child")...)
|
||||
children[i].Stdout = os.Stdout
|
||||
children[i].Stderr = os.Stderr
|
||||
children[i].ExtraFiles = []*os.File{fl}
|
||||
if err := children[i].Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, ch := range children {
|
||||
if err := ch.Wait(); err != nil {
|
||||
log.Print(err)
|
||||
}
|
||||
}
|
||||
os.Exit(0)
|
||||
} else {
|
||||
fmt.Printf(" \x1b[1;30mChild \x1b[1;32m#%v\x1b[1;30m reuseport\x1b[1;32m%s\x1b[0000m\n", os.Getpid(), host)
|
||||
var err error
|
||||
listener, err = net.FileListener(os.NewFile(3, ""))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
runtime.GOMAXPROCS(1)
|
||||
}
|
||||
return listener, nil
|
||||
}
|
||||
|
|
|
@ -0,0 +1,63 @@
|
|||
// 🚀 Fiber, Express on Steriods
|
||||
// 📌 Don't use in production until version 1.0.0
|
||||
// 🖥 https://github.com/gofiber/fiber
|
||||
|
||||
// 🦸 Not all heroes wear capes, thank you to some amazing people
|
||||
// 💖 @valyala, @dgrr, @erikdubbelboer, @savsgio, @julienschmidt
|
||||
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Static ...
|
||||
func (r *Fiber) Static(args ...string) {
|
||||
prefix := "/"
|
||||
root := "./"
|
||||
wildcard := false
|
||||
gzip := true
|
||||
if len(args) == 1 {
|
||||
root = args[0]
|
||||
} else if len(args) == 2 {
|
||||
prefix = args[0]
|
||||
root = args[1]
|
||||
if prefix[0] != '/' {
|
||||
prefix = "/" + prefix
|
||||
}
|
||||
}
|
||||
// Check if wildcard for single files
|
||||
if prefix == "*" || prefix == "/*" {
|
||||
wildcard = true
|
||||
}
|
||||
// Lets get all files from root
|
||||
files, _, err := walkDir(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" {
|
||||
r.routes = append(r.routes, &route{"GET", prefix, wildcard, 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, nil, nil, func(c *Ctx) {
|
||||
c.SendFile(filePath, gzip)
|
||||
}})
|
||||
}
|
||||
}
|
189
status.go
189
status.go
|
@ -9,135 +9,66 @@ package fiber
|
|||
|
||||
// Credits @valyala
|
||||
// https://github.com/valyala/fasthttp/blob/master/status.go
|
||||
const (
|
||||
StatusContinue = 100 // RFC 7231, 6.2.1
|
||||
StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
|
||||
StatusProcessing = 102 // RFC 2518, 10.1
|
||||
|
||||
StatusOK = 200 // RFC 7231, 6.3.1
|
||||
StatusCreated = 201 // RFC 7231, 6.3.2
|
||||
StatusAccepted = 202 // RFC 7231, 6.3.3
|
||||
StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
|
||||
StatusNoContent = 204 // RFC 7231, 6.3.5
|
||||
StatusResetContent = 205 // RFC 7231, 6.3.6
|
||||
StatusPartialContent = 206 // RFC 7233, 4.1
|
||||
StatusMultiStatus = 207 // RFC 4918, 11.1
|
||||
StatusAlreadyReported = 208 // RFC 5842, 7.1
|
||||
StatusIMUsed = 226 // RFC 3229, 10.4.1
|
||||
|
||||
StatusMultipleChoices = 300 // RFC 7231, 6.4.1
|
||||
StatusMovedPermanently = 301 // RFC 7231, 6.4.2
|
||||
StatusFound = 302 // RFC 7231, 6.4.3
|
||||
StatusSeeOther = 303 // RFC 7231, 6.4.4
|
||||
StatusNotModified = 304 // RFC 7232, 4.1
|
||||
StatusUseProxy = 305 // RFC 7231, 6.4.5
|
||||
// StatusSwitchProxy = 306 // RFC 7231, 6.4.6 (Unused)
|
||||
StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
|
||||
StatusPermanentRedirect = 308 // RFC 7538, 3
|
||||
|
||||
StatusBadRequest = 400 // RFC 7231, 6.5.1
|
||||
StatusUnauthorized = 401 // RFC 7235, 3.1
|
||||
StatusPaymentRequired = 402 // RFC 7231, 6.5.2
|
||||
StatusForbidden = 403 // RFC 7231, 6.5.3
|
||||
StatusNotFound = 404 // RFC 7231, 6.5.4
|
||||
StatusMethodNotAllowed = 405 // RFC 7231, 6.5.5
|
||||
StatusNotAcceptable = 406 // RFC 7231, 6.5.6
|
||||
StatusProxyAuthRequired = 407 // RFC 7235, 3.2
|
||||
StatusRequestTimeout = 408 // RFC 7231, 6.5.7
|
||||
StatusConflict = 409 // RFC 7231, 6.5.8
|
||||
StatusGone = 410 // RFC 7231, 6.5.9
|
||||
StatusLengthRequired = 411 // RFC 7231, 6.5.10
|
||||
StatusPreconditionFailed = 412 // RFC 7232, 4.2
|
||||
StatusRequestEntityTooLarge = 413 // RFC 7231, 6.5.11
|
||||
StatusRequestURITooLong = 414 // RFC 7231, 6.5.12
|
||||
StatusUnsupportedMediaType = 415 // RFC 7231, 6.5.13
|
||||
StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
|
||||
StatusExpectationFailed = 417 // RFC 7231, 6.5.14
|
||||
StatusTeapot = 418 // RFC 7168, 2.3.3
|
||||
StatusUnprocessableEntity = 422 // RFC 4918, 11.2
|
||||
StatusLocked = 423 // RFC 4918, 11.3
|
||||
StatusFailedDependency = 424 // RFC 4918, 11.4
|
||||
StatusUpgradeRequired = 426 // RFC 7231, 6.5.15
|
||||
StatusPreconditionRequired = 428 // RFC 6585, 3
|
||||
StatusTooManyRequests = 429 // RFC 6585, 4
|
||||
StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5
|
||||
StatusUnavailableForLegalReasons = 451 // RFC 7725, 3
|
||||
|
||||
StatusInternalServerError = 500 // RFC 7231, 6.6.1
|
||||
StatusNotImplemented = 501 // RFC 7231, 6.6.2
|
||||
StatusBadGateway = 502 // RFC 7231, 6.6.3
|
||||
StatusServiceUnavailable = 503 // RFC 7231, 6.6.4
|
||||
StatusGatewayTimeout = 504 // RFC 7231, 6.6.5
|
||||
StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6
|
||||
StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1
|
||||
StatusInsufficientStorage = 507 // RFC 4918, 11.5
|
||||
StatusLoopDetected = 508 // RFC 5842, 7.2
|
||||
StatusNotExtended = 510 // RFC 2774, 7
|
||||
StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
|
||||
)
|
||||
|
||||
var statusMessages = map[int]string{
|
||||
StatusContinue: "Continue",
|
||||
StatusSwitchingProtocols: "Switching Protocols",
|
||||
StatusProcessing: "Processing",
|
||||
|
||||
StatusOK: "OK",
|
||||
StatusCreated: "Created",
|
||||
StatusAccepted: "Accepted",
|
||||
StatusNonAuthoritativeInfo: "Non-Authoritative Information",
|
||||
StatusNoContent: "No Content",
|
||||
StatusResetContent: "Reset Content",
|
||||
StatusPartialContent: "Partial Content",
|
||||
StatusMultiStatus: "Multi-Status",
|
||||
StatusAlreadyReported: "Already Reported",
|
||||
StatusIMUsed: "IM Used",
|
||||
|
||||
StatusMultipleChoices: "Multiple Choices",
|
||||
StatusMovedPermanently: "Moved Permanently",
|
||||
StatusFound: "Found",
|
||||
StatusSeeOther: "See Other",
|
||||
StatusNotModified: "Not Modified",
|
||||
StatusUseProxy: "Use Proxy",
|
||||
StatusTemporaryRedirect: "Temporary Redirect",
|
||||
StatusPermanentRedirect: "Permanent Redirect",
|
||||
|
||||
StatusBadRequest: "Bad Request",
|
||||
StatusUnauthorized: "Unauthorized",
|
||||
StatusPaymentRequired: "Payment Required",
|
||||
StatusForbidden: "Forbidden",
|
||||
StatusNotFound: "Not Found",
|
||||
StatusMethodNotAllowed: "Method Not Allowed",
|
||||
StatusNotAcceptable: "Not Acceptable",
|
||||
StatusProxyAuthRequired: "Proxy Authentication Required",
|
||||
StatusRequestTimeout: "Request Timeout",
|
||||
StatusConflict: "Conflict",
|
||||
StatusGone: "Gone",
|
||||
StatusLengthRequired: "Length Required",
|
||||
StatusPreconditionFailed: "Precondition Failed",
|
||||
StatusRequestEntityTooLarge: "Request Entity Too Large",
|
||||
StatusRequestURITooLong: "Request URI Too Long",
|
||||
StatusUnsupportedMediaType: "Unsupported Media Type",
|
||||
StatusRequestedRangeNotSatisfiable: "Requested Range Not Satisfiable",
|
||||
StatusExpectationFailed: "Expectation Failed",
|
||||
StatusTeapot: "I'm a teapot",
|
||||
StatusUnprocessableEntity: "Unprocessable Entity",
|
||||
StatusLocked: "Locked",
|
||||
StatusFailedDependency: "Failed Dependency",
|
||||
StatusUpgradeRequired: "Upgrade Required",
|
||||
StatusPreconditionRequired: "Precondition Required",
|
||||
StatusTooManyRequests: "Too Many Requests",
|
||||
StatusRequestHeaderFieldsTooLarge: "Request Header Fields Too Large",
|
||||
StatusUnavailableForLegalReasons: "Unavailable For Legal Reasons",
|
||||
|
||||
StatusInternalServerError: "Internal Server Error",
|
||||
StatusNotImplemented: "Not Implemented",
|
||||
StatusBadGateway: "Bad Gateway",
|
||||
StatusServiceUnavailable: "Service Unavailable",
|
||||
StatusGatewayTimeout: "Gateway Timeout",
|
||||
StatusHTTPVersionNotSupported: "HTTP Version Not Supported",
|
||||
StatusVariantAlsoNegotiates: "Variant Also Negotiates",
|
||||
StatusInsufficientStorage: "Insufficient Storage",
|
||||
StatusLoopDetected: "Loop Detected",
|
||||
StatusNotExtended: "Not Extended",
|
||||
StatusNetworkAuthenticationRequired: "Network Authentication Required",
|
||||
100: "Continue",
|
||||
101: "Switching Protocols",
|
||||
102: "Processing",
|
||||
200: "OK",
|
||||
201: "Created",
|
||||
202: "Accepted",
|
||||
203: "Non-Authoritative Information",
|
||||
204: "No Content",
|
||||
205: "Reset Content",
|
||||
206: "Partial Content",
|
||||
207: "Multi-Status",
|
||||
208: "Already Reported",
|
||||
226: "IM Used",
|
||||
300: "Multiple Choices",
|
||||
301: "Moved Permanently",
|
||||
302: "Found",
|
||||
303: "See Other",
|
||||
304: "Not Modified",
|
||||
305: "Use Proxy",
|
||||
// 306:"Switch Proxy",
|
||||
307: "Temporary Redirect",
|
||||
308: "Permanent Redirect",
|
||||
400: "Bad Request",
|
||||
401: "Unauthorized",
|
||||
402: "Payment Required",
|
||||
403: "Forbidden",
|
||||
404: "Not Found",
|
||||
405: "Method Not Allowed",
|
||||
406: "Not Acceptable",
|
||||
407: "Proxy Authentication Required",
|
||||
408: "Request Timeout",
|
||||
409: "Conflict",
|
||||
410: "Gone",
|
||||
411: "Length Required",
|
||||
412: "Precondition Failed",
|
||||
413: "Request Entity Too Large",
|
||||
414: "Request URI Too Long",
|
||||
415: "Unsupported Media Type",
|
||||
416: "Requested Range Not Satisfiable",
|
||||
417: "Expectation Failed",
|
||||
418: "I'm a teapot",
|
||||
422: "Unprocessable Entity",
|
||||
423: "Locked",
|
||||
424: "Failed Dependency",
|
||||
426: "Upgrade Required",
|
||||
428: "Precondition Required",
|
||||
429: "Too Many Requests",
|
||||
431: "Request Header Fields Too Large",
|
||||
451: "Unavailable For Legal Reasons",
|
||||
500: "Internal Server Error",
|
||||
501: "Not Implemented",
|
||||
502: "Bad Gateway",
|
||||
503: "Service Unavailable",
|
||||
504: "Gateway Timeout",
|
||||
505: "HTTP Version Not Supported",
|
||||
506: "Variant Also Negotiates",
|
||||
507: "Insufficient Storage",
|
||||
508: "Loop Detected",
|
||||
510: "Not Extended",
|
||||
511: "Network Authentication Required",
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue