From 2730e0c2ff7ed3056160e3e64c392e69cc1048dc Mon Sep 17 00:00:00 2001 From: Fenny Date: Mon, 20 Jan 2020 04:33:55 +0100 Subject: [PATCH] v1.0.0-pre-release --- .travis.yml | 10 - CODE_OF_CONDUCT.md | 76 ------ README.md | 33 ++- context.go | 575 ---------------------------------------- docs/application.md | 172 +++++++----- docs/benchmarks.md | 2 + docs/context.md | 21 +- docs/examples.md | 83 +++--- docs/getting_started.md | 35 ++- docs/index.html | 2 +- fiber.go | 106 ++++++++ go.sum | 26 ++ listen.go | 142 ++++++++++ methods.go | 71 +++++ request.go | 286 ++++++++++++++++++++ response.go | 305 +++++++++++++++++++++ router.go | 335 ----------------------- static.go | 63 +++++ status.go | 189 +++++-------- 19 files changed, 1259 insertions(+), 1273 deletions(-) delete mode 100644 .travis.yml delete mode 100644 CODE_OF_CONDUCT.md create mode 100644 fiber.go create mode 100644 listen.go create mode 100644 methods.go create mode 100644 request.go create mode 100644 response.go create mode 100644 static.go diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 35b72d02..00000000 --- a/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: go -go: - - 1.3.3 - - 1.4.2 - - 1.5.1 - - release - - tip - -script: - - go test -v ./... diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 9f1daa38..00000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -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 diff --git a/README.md b/README.md index 732926e1..0f4292dd 100644 --- a/README.md +++ b/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) } ``` diff --git a/context.go b/context.go index 6f266da2..5b114e96 100644 --- a/context.go +++ b/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" -} diff --git a/docs/application.md b/docs/application.md index 3a32be84..2787beac 100644 --- a/docs/application.md +++ b/docs/application.md @@ -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. + +![](https://i.imgur.com/96l7g9l.png) + ```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. + + + +
+ +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") ``` diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 0cd021f0..69de4399 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -57,3 +57,5 @@ If we enable http pipelining, test result as below: CPU-Bound Test ![](static/benchmarks/cpubound_benchmark.png) + +*Caught a mistake? [Edit this page on GitHub!](https://github.com/Fenny/fiber/blob/master/docs/benchmarks.md)* diff --git a/docs/context.md b/docs/context.md index 54e672a2..2a431656 100644 --- a/docs/context.md +++ b/docs/context.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. diff --git a/docs/examples.md b/docs/examples.md index 54358ae5..923da10d 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -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)* diff --git a/docs/getting_started.md b/docs/getting_started.md index c103a82b..dc930db8 100644 --- a/docs/getting_started.md +++ b/docs/getting_started.md @@ -6,7 +6,7 @@ [![Join the chat at https://gitter.im/FiberGo/community](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/FiberGo/community)
# 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/)**.
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 }) ``` diff --git a/docs/index.html b/docs/index.html index 05658a55..048f0598 100644 --- a/docs/index.html +++ b/docs/index.html @@ -19,7 +19,7 @@