⚡️ Express inspired web framework written in Go

Fiber

Fiber is an Express inspired web framework built on top of Fasthttp, the fastest HTTP engine for Go. Designed to ease things up for fast development with zero memory allocation and performance in mind.

⚡️ Quickstart

package main

import "github.com/gofiber/fiber/v2"

func main() {
    app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World 👋!")
    })

    app.Listen(":3000")
}

🤖 Benchmarks

These tests are performed by TechEmpower and Go Web. If you want to see all results, please visit our Wiki.

⚙️ Installation

Make sure you have Go installed (download). Version 1.14 or higher is required.

Initialize your project by creating a folder and then running go mod init github.com/your/repo (learn more) inside the folder. Then install Fiber with the go get command:

go get -u github.com/gofiber/fiber/v2

🎯 Features

💡 Philosophy

New gophers that make the switch from Node.js to Go are dealing with a learning curve before they can start building their web applications or microservices. Fiber, as a web framework, was created with the idea of minimalism and follows the UNIX way, so that new gophers can quickly enter the world of Go with a warm and trusted welcome.

Fiber is inspired by Express, the most popular web framework on the Internet. We combined the ease of Express and raw performance of Go. If you have ever implemented a web application in Node.js (using Express or similar), then many methods and principles will seem very common to you.

We listen to our users in issues, Discord channel and all over the Internet to create a fast, flexible and friendly Go web framework for any task, deadline and developer skill! Just like Express does in the JavaScript world.

👀 Examples

Listed below are some of the common examples. If you want to see more code examples , please visit our Recipes repository or visit our hosted API documentation.

📖 Basic Routing

func main() {
    app := fiber.New()

    // GET /john
    app.Get("/:name", func(c *fiber.Ctx) error {
        msg := fmt.Sprintf("Hello, %s 👋!", c.Params("name"))
        return c.SendString(msg) // => Hello john 👋!
    })

    // GET /john/75
    app.Get("/:name/:age/:gender?", func(c *fiber.Ctx) error {
        msg := fmt.Sprintf("👴 %s is %s years old", c.Params("name"), c.Params("age"))
        return c.SendString(msg) // => 👴 john is 75 years old
    })

    // GET /dictionary.txt
    app.Get("/:file.:ext", func(c *fiber.Ctx) error {
        msg := fmt.Sprintf("📃 %s.%s", c.Params("file"), c.Params("ext"))
        return c.SendString(msg) // => 📃 dictionary.txt
    })

    // GET /flights/LAX-SFO
    app.Get("/flights/:from-:to", func(c *fiber.Ctx) error {
        msg := fmt.Sprintf("💸 From: %s, To: %s", c.Params("from"), c.Params("to"))
        return c.SendString(msg) // => 💸 From: LAX, To: SFO
    })

    // GET /api/register
    app.Get("/api/*", func(c *fiber.Ctx) error {
        msg := fmt.Sprintf("✋ %s", c.Params("*"))
        return c.SendString(msg) // => ✋ register
    })

    log.Fatal(app.Listen(":3000"))
}

📖 Serving Static Files

func main() {
    app := fiber.New()

    app.Static("/", "./public")
    // => http://localhost:3000/js/script.js
    // => http://localhost:3000/css/style.css

    app.Static("/prefix", "./public")
    // => http://localhost:3000/prefix/js/script.js
    // => http://localhost:3000/prefix/css/style.css

    app.Static("*", "./public/index.html")
    // => http://localhost:3000/any/path/shows/index/html

    log.Fatal(app.Listen(":3000"))
}

📖 Middleware & Next

func main() {
    app := fiber.New()

    // Match any route
    app.Use(func(c *fiber.Ctx) error {
        fmt.Println("🥇 First handler")
        return c.Next()
    })

    // Match all routes starting with /api
    app.Use("/api", func(c *fiber.Ctx) error {
        fmt.Println("🥈 Second handler")
        return c.Next()
    })

    // GET /api/register
    app.Get("/api/list", func(c *fiber.Ctx) error {
        fmt.Println("🥉 Last handler")
        return c.SendString("Hello, World 👋!")
    })

    log.Fatal(app.Listen(":3000"))
}
📚 Show more code examples

Views engines

📖 Config 📖 Engines 📖 Render

Fiber defaults to the html/template when no view engine is set.

If you want to execute partials or use a different engine like amber, handlebars, mustache or pug etc..

Checkout our Template package that support multiple view engines.

package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/template/pug"
)

func main() {
    // You can setup Views engine before initiation app:
    app := fiber.New(fiber.Config{
        Views: pug.New("./views", ".pug"),
    })

    // And now, you can call template `./views/home.pug` like this:
    app.Get("/", func(c *fiber.Ctx) error {
        return c.Render("home", fiber.Map{
            "title": "Homepage",
            "year":  1999,
        })
    })

    log.Fatal(app.Listen(":3000"))
}

Grouping routes into chains

📖 Group

func middleware(c *fiber.Ctx) error {
    fmt.Println("Don't mind me!")
    return c.Next()
}

func handler(c *fiber.Ctx) error {
    return c.SendString(c.Path())
}

func main() {
    app := fiber.New()

    // Root API route
    api := app.Group("/api", middleware) // /api

    // API v1 routes
    v1 := api.Group("/v1", middleware) // /api/v1
    v1.Get("/list", handler)           // /api/v1/list
    v1.Get("/user", handler)           // /api/v1/user

    // API v2 routes
    v2 := api.Group("/v2", middleware) // /api/v2
    v2.Get("/list", handler)           // /api/v2/list
    v2.Get("/user", handler)           // /api/v2/user

    // ...
}

Middleware logger

📖 Logger

package main

import (
    "log"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/logger"
)

func main() {
    app := fiber.New()

    app.Use(logger.New())

    // ...

    log.Fatal(app.Listen(":3000"))
}

Cross-Origin Resource Sharing (CORS)

📖 CORS

import (
    "log"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/cors"
)

func main() {
    app := fiber.New()

    app.Use(cors.New())

    // ...

    log.Fatal(app.Listen(":3000"))
}

Check CORS by passing any domain in Origin header:

curl -H "Origin: http://example.com" --verbose http://localhost:3000

Custom 404 response

📖 HTTP Methods

func main() {
    app := fiber.New()

    app.Static("/", "./public")

    app.Get("/demo", func(c *fiber.Ctx) error {
        return c.SendString("This is a demo!")
    })

    app.Post("/register", func(c *fiber.Ctx) error {
        return c.SendString("Welcome!")
    })

    // Last middleware to match anything
    app.Use(func(c *fiber.Ctx) error {
        return c.SendStatus(404)
        // => 404 "Not Found"
    })

    log.Fatal(app.Listen(":3000"))
}

JSON Response

📖 JSON

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    app := fiber.New()

    app.Get("/user", func(c *fiber.Ctx) error {
        return c.JSON(&User{"John", 20})
        // => {"name":"John", "age":20}
    })

    app.Get("/json", func(c *fiber.Ctx) error {
        return c.JSON(fiber.Map{
            "success": true,
            "message": "Hi John!",
        })
        // => {"success":true, "message":"Hi John!"}
    })

    log.Fatal(app.Listen(":3000"))
}

WebSocket Upgrade

📖 Websocket

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/websocket"
)

func main() {
  app := fiber.New()

  app.Get("/ws", websocket.New(func(c *websocket.Conn) {
    for {
      mt, msg, err := c.ReadMessage()
      if err != nil {
        log.Println("read:", err)
        break
      }
      log.Printf("recv: %s", msg)
      err = c.WriteMessage(mt, msg)
      if err != nil {
        log.Println("write:", err)
        break
      }
    }
  }))

  log.Fatal(app.Listen(":3000"))
  // ws://localhost:3000/ws
}

Recover middleware

📖 Recover

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/recover"
)

func main() {
    app := fiber.New()

    app.Use(recover.New())

    app.Get("/", func(c *fiber.Ctx) error {
        panic("normally this would crash your app")
    })

    log.Fatal(app.Listen(":3000"))
}

🧬 Internal Middleware

Here is a list of middleware that are included within the Fiber framework.

Middleware Description
basicauth Basic auth middleware provides an HTTP basic authentication. It calls the next handler for valid credentials and 401 Unauthorized for missing or invalid credentials.
compress Compression middleware for Fiber, it supports deflate, gzip and brotli by default.
cache Intercept and cache responses
cors Enable cross-origin resource sharing (CORS) with various options.
csrf Protect from CSRF exploits.
filesystem FileSystem middleware for Fiber, special thanks and credits to Alireza Salary
favicon Ignore favicon from logs or serve from memory if a file path is provided.
limiter Rate-limiting middleware for Fiber. Use to limit repeated requests to public APIs and/or endpoints such as password reset.
logger HTTP request/response logger.
pprof Special thanks to Matthew Lee (@mthli)
proxy Allows you to proxy requests to a multiple servers
requestid Adds a requestid to every request.
recover Recover middleware recovers from panics anywhere in the stack chain and handles the control to the centralized ErrorHandler.
timeout Adds a max time for a request and forwards to ErrorHandler if it is exceeded.

🧬 External Middleware

List of externally hosted middleware modules and maintained by the Fiber team.

Middleware Description
adaptor Converter for net/http handlers to/from Fiber request handlers, special thanks to @arsmn!
helmet Helps secure your apps by setting various HTTP headers.
jwt JWT returns a JSON Web Token (JWT) auth middleware.
keyauth Key auth middleware provides a key based authentication.
rewrite Rewrite middleware rewrites the URL path based on provided rules. It can be helpful for backward compatibility or just creating cleaner and more descriptive links.
session This session middleware is build on top of fasthttp/session by @savsgio MIT. Special thanks to @thomasvvugt for helping with this middleware.
template This package contains 8 template engines that can be used with Fiber v1.10.x Go version 1.13 or higher is required.
websocket Based on Fasthttp WebSocket for Fiber with Locals support!

🌱 Third Party Middlewares

This is a list of middlewares that are created by the Fiber community, please create a PR if you want to see yours!

👍 Contribute

If you want to say thank you and/or support the active development of Fiber:

  1. Add a GitHub Star to the project.
  2. Tweet about the project on your Twitter.
  3. Write a review or tutorial on Medium, Dev.to or personal blog.
  4. Support the project by donating a cup of coffee.

Supporters

Fiber is an open source project that runs on donations to pay the bills e.g. our domain name, gitbook, netlify and serverless hosting. If you want to support Fiber, you can buy a coffee here.

User Donation
@destari x 10
@dembygenesis x 5
@thomasvvugt x 5
@hendratommy x 5
@ekaputra07 x 5
@jorgefuertes x 5
@candidosales x 5
@l0nax x 3
@ankush x 3
@bihe x 3
@justdave x 3
@koddr x 1
@lapolinar x 1
@diegowifi x 1
@ssimk0 x 1
@raymayemir x 1
@melkorm x 1
@marvinjwendt x 1
@toishy x 1

‎‍💻 Code Contributors

Code Contributors

⭐️ Stargazers

Stargazers over time

⚠️ License

Copyright (c) 2019-present Fenny and Contributors. Fiber is free and open-source software licensed under the MIT License. Official logo was created by Vic Shóstak and distributed under Creative Commons license (CC BY-SA 4.0 International).

Third-party library licenses

Owner
Fiber
🚀 Fiber is an Express inspired web framework written in Go with 💖
Fiber
Comments
  • 💡 v3 discussion

    💡 v3 discussion

    Fiber

    Dear Gophers, we think it's a good idea to start discussions regarding the v3. You are welcome to join us on discord where we created a dedicated channel to pin suggestions for the next update .

  • :sparkles: Add customTags in logger middleware Config

    :sparkles: Add customTags in logger middleware Config

    Description

    Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. Explain the details for making this change. What existing problem does the pull request solve?

    Fixes https://github.com/gofiber/fiber/issues/2187

    Type of change

    Please delete options that are not relevant.

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [x] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
    • [ ] This change requires a documentation update

    Checklist:

    • [x] For new functionalities I follow the inspiration of the express js framework and built them similar in usage
    • [x] I have performed a self-review of my own code
    • [x] I have commented my code, particularly in hard-to-understand areas
    • [ ] I have made corresponding changes to the documentation - https://github.com/gofiber/docs for https://docs.gofiber.io/
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] New and existing unit tests pass locally with my changes
    • [x] If new dependencies exist, I have checked that they are really necessary and agreed with the maintainers/community (we want to have as few dependencies as possible)
    • [x] I tried to make my code as fast as possible with as few allocations as possible
    • [x] For new code I have written benchmarks so that they can be analyzed and improved

    Commit formatting:

    Use emojis on commit messages so it provides an easy way of identifying the purpose or intention of a commit. Check out the emoji cheatsheet here: https://gitmoji.carloscuesta.me/

  •  🚀 Request: Route Constraints

    🚀 Request: Route Constraints

    Route constraints execute when a match has occurred to the incoming URL and the URL path is tokenized into route values. I found this very useful when defining routes. ASP NET Core was inspiration for this feature.

    Example

      app.Get("/users/{id:int}", func (ctx *fiber.Ctx) {
          // will come here if id is int
         // otherwise return 404
      })
    

    Proposed constraints:

    | Constraint | Example | Example matches | | ----------- | -------------- | ------------------------- | | int | {id:int} | 123456789, -123456789 | | bool | {active:bool} | true,false | | datetime | {dob:datetime} | 2016-12-31, 2016-12-31 7:32pm | | guid | {id:guid} | CD2C1638-1638-72D5-1638-DEADBEEF1638| | float | {weight:float} | 1.234, -1,001.01e8 | | minlength(value) | {username:minlength(4)} | Test (must be at least 4 characters) | | maxlength(value) | {filename:maxlength(8)} | MyFile (must be no more than 8 characters | | length(length) | {filename:length(12)} | somefile.txt (exactly 12 characters) | | min(value) | {age:min(18)} | 19 (Integer value must be at least 18) | | max(value) | {age:max(120)} | 91 (Integer value must be no more than 120) | | range(min,max) | {age:range(18,120)} | 91 (Integer value must be at least 18 but no more than 120) | | alpha | {name:alpha} | Rick (String must consist of one or more alphabetical characters, a-z and case-insensitive) | | regex(expression) | {ssn:regex(^\d{{3}}-\d{{2}}-\d{{4}}$)} | 123-45-6789 (Must match regular expression) |

    More details: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-6.0#route-constraints

  • Use sliding window instead of fixed window algorithm in limiter middleware

    Use sliding window instead of fixed window algorithm in limiter middleware

    Please provide enough information so that others can review your pull request:

    Refactored the rate limiter to use a sliding window algorithm instead of fixed window. Added a new test that can demonstrate how to "cheat" the old rate limiting algorithm.

    Explain the details for making this change. What existing problem does the pull request solve?

    Sliding window algorithm offers significant improvement over the fixed window algorithm and has very little overhead for this gain. Fixed window makes it possible for an API consumer to wait for a reset window and then send more requests, cheating the allowed limit.

    Commit formatting

    Use emojis on commit messages so it provides an easy way of identifying the purpose or intention of a commit. Check out the emoji cheatsheet here: https://gitmoji.carloscuesta.me/

  • ✨ v3 (feature): add retry mechanism

    ✨ v3 (feature): add retry mechanism

    • General logic is implemented.
    • Unit tests are added.

    Signed-off-by: Gökhan Özeloğlu [email protected]

    Please provide enough information so that others can review your pull request: It is related to #1840.

    Explain the details for making this change. What existing problem does the pull request solve?

    I added a new package called retry. Exponential backoff algorithm is used. I can refactor the code like constant/default values, tests, etc. I am going to add more tests and maybe I'll do some small changes to the code.

  • 🐛 ClearCookie does not remove cookie

    🐛 ClearCookie does not remove cookie

    Fiber version v2

    Issue description ClearCookie does not remove cookie

    Code snippet

    I have 2 routes.

    1. a POST Sign in route to set the cookie
    cookie := new(fiber.Cookie)
    cookie.Name = "JWT"
    cookie.Value = "....."
    cookie.Domain = "mydomain.com"
    cookie.HTTPOnly = true
    cookie.Expires = expires
    
    c.Cookie(cookie)
    
    

    and second route is a POST for sign out which removes the cookie

    c.ClearCookie("JWT")
    

    In chrome, the cookie continues to exist after Sign Out and user able to make calls to restricted routes. Chrome Version 87.0.4280.141 (Official Build) (x86_64)

  • Can't able to set request header to Access-Control-Allow-Origin🤗

    Can't able to set request header to Access-Control-Allow-Origin🤗

    Question description Guys I am a big fan of your work, I was just making an api to work with my react app. But Access-Control-Allow-Origin cors issue is coming up. I checked AllowOrigins was set to * in default, I manually tried it too. Then I tried to add to AllowHeaders but nothing seem to work. I read upon the Config struct and it seem to set it when its either "*" or a specific domain but in my case none works. I am doing something wrong?

    Code snippet Optional

    	app.Use(cors.New(cors.Config{
    		AllowCredentials: true,
    		AllowOrigins:     "https://gradbook-cet.netlify.com",
    		AllowHeaders:     "Origin, Content-Type, Accept, Accept-Language, Content-Length",
    	}))
    
    
  • 🤗 What's the main difference in the throughout between v1.* and v2.*?

    🤗 What's the main difference in the throughout between v1.* and v2.*?

    Question description I had some stress tests on fiber v1.14.6 by accessing a local sqlite (query a few records) or remote redis (get a short string value) and found that the result throughtput can up to around 12000 requests/s.

    import "github.com/gofiber/fiber"
    

    But the above sentence actually downloads and uses fiber v1.14.6, rather than v2.*. What I wonder is how to let it use fiber v2 instead and the performance diference between the two major versions.

    Code snippet Optional

    
    import (
            "fmt"     
    
            "qc.com/m/v1/book"                    
            "qc.com/m/v1/database"             
            "github.com/gofiber/fiber"
            "github.com/jinzhu/gorm"
            _ "github.com/jinzhu/gorm/dialects/sqlite"
    )
    
    
    func setupRoutes(app *fiber.App) {  
            app.Get("/api/v1/book", book.GetBooks)
    }
    
    func initDatabase() {
            var err error
            database.DBConn, err = gorm.Open("sqlite3", "books.db")
            if err != nil {
                    panic("failed to connect database")
            }
            fmt.Println("Connection Opened to Database")
            database.DBConn.AutoMigrate(&book.Book{})
            fmt.Println("Database Migrated")
    }
    
    func main() {
            app := fiber.New()
            initDatabase()
            setupRoutes(app)
            app.Listen(3000)
           
            defer database.DBConn.Close()
    }
    
    
  • 🤔 I'm having issues with go get / git on Windows

    🤔 I'm having issues with go get / git on Windows

    Description

    I am trying to install fiber using go get -u github.com/gofiber/fiber but its throwing me error I have attached below:

    image

    Here is what go env commands prints

    C:\Users\KIIT_Intern\go\src\github.com\pranjal.agni\rest-api-playground>go env
    set GO111MODULE=
    set GOARCH=amd64
    set GOBIN=
    set GOCACHE=C:\Users\KIIT_Intern\AppData\Local\go-build
    set GOENV=C:\Users\KIIT_Intern\AppData\Roaming\go\env
    set GOEXE=.exe
    set GOFLAGS=
    set GOHOSTARCH=amd64
    set GOHOSTOS=windows
    set GOINSECURE=
    set GONOPROXY=
    set GONOSUMDB=
    set GOOS=windows
    set GOPATH=C:\Users\KIIT_Intern\go
    set GOPRIVATE=
    set GOPROXY=https://proxy.golang.org,direct
    set GOROOT=c:\go
    set GOSUMDB=sum.golang.org
    set GOTMPDIR=
    set GOTOOLDIR=c:\go\pkg\tool\windows_amd64
    set GCCGO=gccgo
    set AR=ar
    set CC=gcc
    set CXX=g++
    set CGO_ENABLED=1
    set GOMOD=
    set CGO_CFLAGS=-g -O2
    set CGO_CPPFLAGS=
    set CGO_CXXFLAGS=-g -O2
    set CGO_FFLAGS=-g -O2
    set CGO_LDFLAGS=-g -O2
    set PKG_CONFIG=pkg-config
    set GOGCCFLAGS=-m64 -mthreads -fmessage-length=0 -fdebug-prefix-map=C:\Users\KIIT_I~1\AppData\Local\Temp\go-build932757670=/tmp/go-build -gno-record-gcc-switches
    

    I wanted to play and learn fiber but unable to fix this issue for quite some time.

    Version

    Golang 1.14.2 windows/amd64 Windows 10 Git version 2.26.0

  • 🐛 Cache Middleware - Update expiration for expired entry

    🐛 Cache Middleware - Update expiration for expired entry

    Please provide enough information so that others can review your pull request: I noticed that expiration timestamp is still the same after cache entry has been expired. It leads to situation when right after the entry has been expired, all the next requests that were made right after the eviction are not cached since the expiration time is always behind the expiration deadline.

    -> call - miss
    -> call - hit
    -> call - hit
    -> call - hit
    ...
    (wait for expiration)
    ...
    (now we'll make the calls right after each other)
    -> call - miss
    -> call - miss
    -> call - miss
    ....
    

    This PR contains one-liner fix and updated test.

  • 📢 v2 - Changelog

    📢 v2 - Changelog

    Updated September 14, 2020 ( 🚀 v2 benchmark results )

    Fiber

    Dear Gophers, after long discussions in our , we decided to release v2.0.0 on 15 September 2020. We will summarize our current API proposal in this post, feedback is more than welcome.


    Breaking Changes

    • func(c *fiber.Ctx) error is the new Handler type accepting an error return, this will simplify error handling and create cleaner code because you can directly return outgoing methods like ***c.Send()***, ***c.Next()***, ***c.SendStatus()***, c.Redirect() etc... https://github.com/gofiber/fiber/issues/218
    // func(c *fiber.Ctx) {}
       func(c *fiber.Ctx) error {}
    
    app.Use(func(c *fiber.Ctx) error {
        if c.Get("x-john") == "doe" {
            return c.Next()
        }
        return c.SendStatus(fiber.StatusForbidden)
    })
    
    app.Use("/teapot", func(c *fiber.Ctx) error {
        return c.Send([]byte("Helllo, Teapot ☕!"))
    })
    
    app.Get("/world", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World 👋!")
    })
    
    app.Get("/redirect", func(c *fiber.Ctx) error {
        return c.Redirect("https://google.com")
    })
    
    • fiber.New() takes an optional Config struct as value that will replace the *Settings pointer.
    // func New(settings ...*Settings) *App {}
       func New(config... Config) *App {}
    
    • app.Listen() now contains a strong typed signature accepting an string addr argument. To enable TLS, provide your own listener app.Listener(ln net.Listener) https://github.com/gofiber/fiber/issues/555
    // func (app *App) Listen(address interface{}, tlsconfig ...*tls.Config) error {}
       func (app *App) Listen(addr string) error {}
    
    • app.Listener() will remove the optional *tls.Config argument, this should be set within the given listener. Prefork will be compatible with custom listeners.
    // func (app *App) Listener(ln net.Listener, tlsconfig ...*tls.Config) error {}
       func (app *App) Listener(ln net.Listener) error {}
    
    • c.Next() returns an error to be used with the new Ctx handler signature. Passing an error through c.Next is not necessary anymore since we return all errors within the handler.
    // func (c *Ctx) Next(err ...error) {}
       func (c *Ctx) Next() error {}
    
    • c.Body() now returns []byte type instead of a string
    // func (c *Ctx) Body() string {}
       func (c *Ctx) Body() []byte {}
    
    • c.Write() will comply with the io.Writer interface.
    // func (c *Ctx) Write(bodies ...interface{}) {}
       func (c *Ctx) Write(p []byte) (n int, err error) {}
    
    // func (c *Ctx) Context() context.Context
       func (c *Ctx) Context() *fasthttp.RequestCtx
    
    • app.IsChild() will be available on the package layer
    // func (app *App) IsChild() bool {}
       func IsChild() bool {}
    

    🧹 Updates

    • c.Send() now contains a strong typed signature accepting a single []byte type Other outgoing Send methods also return an error to comply with the new Handler signature
    // func (c *Ctx) Send(bodies ...interface{}) {}
       func (c *Ctx) Send(body []byte) error {}
    
    // func (c *Ctx) SendStatus(status int) {}
       func (c *Ctx) SendStatus(status int) error {}
    
    // func (c *Ctx) SendString(body string) {}
       func (c *Ctx) SendString(body string) error {}
    
    // func (c *Ctx) SendStream(stream io.Reader, size ...int) {}
       func (c *Ctx) SendStream(stream io.Reader, size ...int) error {}
    
    • c.Redirect() now returns an error
    // func (c *Ctx) Redirect(location string, status ...int) {}
       func (c *Ctx) Redirect(location string, status ...int) error {}
    
    • c.FormValue() now supports the optional defaultValue argument
    // func (c *Ctx) FormValue(key string) string {}
       func (c *Ctx) FormValue(key string, defaultValue ...string) string {}
    

    Removed

    • c.SendBytes() will be removed and is replaced by c.Send
    // func (c *Ctx) SendBytes(body []byte) {}
    
    • c.Error() will be removed because errors can be accessed using the error return in c.Next() error
    // func (c *Ctx) Error() error {}
    

    🔥 New

    // c.Fasthttp.Request.Header.Peek("x-version")
       c.Request().Header.Peek("x-version")
    
    // c.Fasthttp.Response.Header.Peek("x-version")
       c.Response().Header.Peek("x-version")
    
    • app.Config.ErrorHandler will replace the app.Settings.ErrorHandler to override the default error handler.
    app := fiber.New(fiber.Config{
    	ErrorHandler: func(c *fiber.Ctx, err error) error {
    		return c.Status(404).SendString("hi, i'm an custom error")
    	},
    })
    
    app.Get("/", func(c *fiber.Ctx) error {
    	return c.SendFile("../there/is/nothing/here")
    })
    
    • Config.ProxyHeader will enable c.IP() to return the value of the given header key. By default c.IP() will return the Remote IP from the tcp connection, this property can be useful if you are behind a load balancer e.g. X-Forwarded-*.
    app := fiber.New(fiber.Config{
    	ProxyHeader: "CF-Connecting-IP",
    })
    app.Get("/", func(c *fiber.Ctx) error {
    	return c.SendString(c.IP()) // value from CF-Connecting-IP header
    })
    
    • Config.GETOnly rejects all non-GET requests if set to true. This option is useful as anti-DoS protection for servers accepting only GET requests and will return an ErrMethodNotAllowed to the error handler. The request size is limited by ReadBufferSize if GETOnly is set. Server accepts all the requests by default.
    app := fiber.New(fiber.Config{
    	GETOnly: true,
    })
    app.Post("/", func(c *fiber.Ctx) error {
    	return c.SendString("This method is not allowed")
    })
    

    🚀 Routing

    • The logic for parsing the route now better recognizes the parts which are not parameters, so the parameter can be placed anywhere, it is only important that the normal non-optional parameters are terminated by a delimiter character:
    // Route
    app.Get("/test::param/", handler)
    // GET /test:fiber/
    
    // Route
    app.Get("/shop/product/color::color/size::size", handler)
    // GET /shop/product/color:blue/size:xs
    
    // Route
    app.Get("/@:name", handler)
    // GET /@Fiber
    
    • Added support for the plus parameter, this is greedy like the wildcard parameter with the difference that it is required:
    // Route
    app.Get("/config/+.json", func(c *fiber.Ctx) error {
    	ctx.Params("+1") //  abc
            ctx.Params("+")   //  abc
    })
    // GET /config/abc.json  // match
    // GET /config/.json     // no match
    
    • Support for multiple wildcard and plus parameters has been added, they can now be accessed via wildcard or plus character with the counter in the route or normally for the first as in the current fiber version:
    // GET /customer/v1/cart/proxy
    app.Get("/*v1*/proxy", func(c *fiber.Ctx) error {
            c.Params("*")    //   customer/
    	c.Params("*1")  //   customer/
    	c.Params("*2")  //   /cart
    })
    

    📦 Middleware

    🚀 Improvements

    • The new version will use the segmentio/encoding package to encode JSON, this will improve performance drastically.
    // v1.14.x
    Benchmark_Ctx_JSON-16            4596667               260 ns/op              64 B/op          2 allocs/op
    Benchmark_Ctx_JSON-16            4603731               259 ns/op              64 B/op          2 allocs/op
    Benchmark_Ctx_JSON-16            4652700               259 ns/op              64 B/op          2 allocs/op
    Benchmark_Ctx_JSON-16            4598620               259 ns/op              64 B/op          2 allocs/op
    
    // v2.0.0
    Benchmark_Ctx_JSON-16            7186842               165 ns/op              64 B/op          2 allocs/op
    Benchmark_Ctx_JSON-16            7214056               164 ns/op              64 B/op          2 allocs/op
    Benchmark_Ctx_JSON-16            7227295               164 ns/op              64 B/op          2 allocs/op
    Benchmark_Ctx_JSON-16            7227291               165 ns/op              64 B/op          2 allocs/op
    
    • 405 Method Not Allowed will be passed to the global error handler, in the old version this behavior was not controllable.
    • This version will ship with fasthttp v1.16.0 which contains the statusLine/statusMessage PR found by @ReneWerner87, @Fenny and @kiyonlin
    • v2.0.0 allows us to implement a hybrid radix tree router which will remove the remaining allocation when CaseSenstitive is disabled and increase performance drasticly. The reason why we went with the hybrid implementation is because we still want to respect the router stack order 😉 thnx @reneWerner87
    // v1.14.x
    Benchmark_Router_NotFound-16                      235243              4843 ns/op              80 B/op          2 allocs/op
    Benchmark_Router_Handler-16                      1721277               696 ns/op              16 B/op          1 allocs/op
    Benchmark_Router_Handler_Strict_Case-16          1848582               651 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_Chain-16                        9300248               129 ns/op               1 B/op          1 allocs/op
    Benchmark_Router_WithCompression-16              8693692               137 ns/op               1 B/op          1 allocs/op
    Benchmark_Router_Next-16                         1960342               619 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_Handler_CaseSensitive-16        1862936               649 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_Handler_Unescape-16              255260              4573 ns/op              16 B/op          1 allocs/op
    Benchmark_Router_Handler_StrictRouting-16        1857168               647 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_Github_API-16                      3634            317628 ns/op               0 B/op          0 allocs/op
    
    // v2.0.0
    Benchmark_Router_NotFound-16                     2919049               411 ns/op              48 B/op          1 allocs/op
    Benchmark_Router_Handler-16                      8331446               145 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_Handler_Strict_Case-16          9675211               124 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_Chain-16                        9088828               132 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_WithCompression-16              9020534               133 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_Next-16                        14454469                81 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_Handler_CaseSensitive-16        9597826               124 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_Handler_Unescape-16             6059216               196 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_Handler_StrictRouting-16        9753892               123 ns/op               0 B/op          0 allocs/op
    Benchmark_Router_Github_API-16                      5452            214098 ns/op               0 B/op          0 allocs/op
    

    See: ( 🚀 v2 benchmark results )

  • 🚀 Feature: Add idempotency middleware (v2 backport)

    🚀 Feature: Add idempotency middleware (v2 backport)

    Description

    Add idempotency middleware. Implements https://github.com/gofiber/fiber/issues/2163.

    This is a v2 backport of https://github.com/gofiber/fiber/pull/2253.

    Type of change

    Please delete options that are not relevant.

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [x] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
    • [x] This change requires a documentation update

    Checklist:

    • [x] For new functionalities I follow the inspiration of the express js framework and built them similar in usage
    • [x] I have performed a self-review of my own code
    • [x] I have commented my code, particularly in hard-to-understand areas
    • [ ] I have made corresponding changes to the documentation - https://github.com/gofiber/docs for https://docs.gofiber.io/
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] New and existing unit tests pass locally with my changes
    • [x] If new dependencies exist, I have checked that they are really necessary and agreed with the maintainers/community (we want to have as few dependencies as possible)
    • [x] I tried to make my code as fast as possible with as few allocations as possible
    • [x] For new code I have written benchmarks so that they can be analyzed and improved
  • Golang fiber c.Render layout not execute with multi templates

    Golang fiber c.Render layout not execute with multi templates

    Question Description

    I'm trying to use one layout with different templates,

    ├── Main Folder
       ├── cmd
            └── main.go
       ├── controllers
       ├── models
       ├── views
            └── partials
                └── layout.html
            └── index.html
            └── dashboard.html
            └── login.html
       └── public
            └── sample.png
    

    In my layout.html, I have

    <!DOCTYPE html>
    <html lang="en">
    <head>
    </head>
    <body>
        <h1>Loaded from Layout</h1>
    
    // this way didn't worked
      {{ template . }}
    
    // so i tried this way also
        {{ $templateName := .Template }}
        {{ template $templateName }}
    
    // both way won't work
    
    
    </body>
    </html>
    

    In my dashboard.html

    {{ define "dashboard" }}
        <h1>Dashboard</h1>
    {{ end }}
    

    In my login.html

    {{ define "login" }}
        <h1>Login</h1>
    {{ end }}
    

    When I'm render dashboard through controller its only load login.html, its take last html file always

    // controller
    
    func Dashboard(c *fiber.Ctx) error {
    	return c.Render("dashboard", fiber.Map{
    		"title": "Login | Selectify Admin",
                    "Template": "dashboard",
    	}, "partials/layout")
    }
    
    

    In main file I have told where to find views

    //main.go
    
    // create a new HTML engine
    	template_engine := html.New(
    		"./views",
    		".html",
    	)
    
    	// create a new Fiber app
    	app := fiber.New(fiber.Config{
    		Views: template_engine, // set the views engine
    
    		ErrorHandler: func(c *fiber.Ctx, err error) error {
    			return utils.HandleError(c, err)
    		},
    	})
    

    it's giving an error "template: "partials/layout" is an incomplete or empty template"

    How can I send or render correct html file using one layout??

    Go version 1.19 fiver version 2 "github.com/gofiber/template/html"

    Code Snippet (optional)

    package main
    
    import "github.com/gofiber/fiber/v2"
    import "log"
    
    func main() {
      app := fiber.New()
    
      // An example to describe the question
    
      log.Fatal(app.Listen(":3000"))
    }
    

    Checklist:

    • [X] I agree to follow Fiber's Code of Conduct.
    • [X] I have checked for existing issues that describe my questions prior to opening this one.
    • [X] I understand that improperly formatted questions may be closed without explanation.
  • 🚀 Feature: Add and apply more stricter golangci-lint linting rules

    🚀 Feature: Add and apply more stricter golangci-lint linting rules

    Description

    In order to fix and avoid upcoming bugs, apply more stricter linting rules while still being easy to maintain.

    Type of change

    Please delete options that are not relevant.

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [x] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
    • [ ] This change requires a documentation update

    Checklist:

    • [x] For new functionalities I follow the inspiration of the express js framework and built them similar in usage
    • [x] I have performed a self-review of my own code
    • [x] I have commented my code, particularly in hard-to-understand areas
    • [x] I have made corresponding changes to the documentation - https://github.com/gofiber/docs for https://docs.gofiber.io/
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] New and existing unit tests pass locally with my changes
    • [x] If new dependencies exist, I have checked that they are really necessary and agreed with the maintainers/community (we want to have as few dependencies as possible)
    • [x] I tried to make my code as fast as possible with as few allocations as possible
    • [x] For new code I have written benchmarks so that they can be analyzed and improved
  • 🚀 [v3 Feature]:

    🚀 [v3 Feature]: "CopyBytes" and "CopyString" should only copy if "config.Immutable" is set

    Feature Description

    Currently, CopyBytes and CopyString make a copy of the underlying data even if not required, i.e., when config.Immutable is set. In order to improve performance, there should be a app.CopyBytes or ctx.CopyBytes which only copies the data if config.Immutable is false.

    Additional Context (optional)

    No response

    Code Snippet (optional)

    No response

    Checklist:

    • [X] I agree to follow Fiber's Code of Conduct.
    • [X] I have checked for existing issues that describe my suggestion prior to opening this one.
    • [X] I understand that improperly formatted feature requests may be closed without explanation.
  • 🐛 [Bug]: A group with blank prefix (

    🐛 [Bug]: A group with blank prefix ("") spills the associated middleware to all the routes added after the group.

    Bug Description

    When the app has a group defined with a blank prefix like so

    group := app.Group("", Middleware)
    

    Any route defined after the group has the Middleware applied regardless. Even the wildcard ones.

    How to Reproduce

    Steps to reproduce the behavior:

    1. Run the code snippet
    2. Request curl localhost:3001/test1
    3. Return the output from the Middleware and NOT the expected out come which Test1!

    Expected Behavior

    localhost:3001/test1 should return Test1!

    Fiber Version

    v2.40.1

    Code Snippet (optional)

    package main
    
    import (
    	"github.com/gofiber/fiber/v2"
    )
    
    func Middleware(c *fiber.Ctx) error {
    	return c.SendString("Middleware!")
    }
    
    func main() {
    	app := fiber.New()
    	app.Get("/", func(c *fiber.Ctx) error {
    		return c.SendString("Hello, World!")
    	})
    
    	group := app.Group("", Middleware)
    	
    	group.Get("/test", func(c *fiber.Ctx) error {
    		return c.SendString("Test!")
    	})
    
    	app.Get("/test1", func(c *fiber.Ctx) error {
    		return c.SendString("Test1!")
    	})
    
    	app.Use("*", func(c *fiber.Ctx) error {
    		return c.SendString("Fallback!")
    	})
    
    	app.Listen(":3001")
    }
    

    Checklist:

    • [X] I agree to follow Fiber's Code of Conduct.
    • [X] I have checked for existing issues that describe my problem prior to opening this one.
    • [X] I understand that improperly formatted bug reports may be closed without explanation.
  • 🚀 Feature: Add earlydata middleware

    🚀 Feature: Add earlydata middleware

    Description

    Add earlydata middleware to add support for TLS 1.3's early data ("0-RTT") feature.

    Type of change

    Please delete options that are not relevant.

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [x] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
    • [x] This change requires a documentation update

    Checklist:

    • [x] For new functionalities I follow the inspiration of the express js framework and built them similar in usage
    • [x] I have performed a self-review of my own code
    • [x] I have commented my code, particularly in hard-to-understand areas
    • [ ] I have made corresponding changes to the documentation - https://github.com/gofiber/docs for https://docs.gofiber.io/
    • [x] I have added tests that prove my fix is effective or that my feature works
    • [x] New and existing unit tests pass locally with my changes
    • [x] If new dependencies exist, I have checked that they are really necessary and agreed with the maintainers/community (we want to have as few dependencies as possible)
    • [x] I tried to make my code as fast as possible with as few allocations as possible
    • [ ] For new code I have written benchmarks so that they can be analyzed and improved
A Go framework for building JSON web services inspired by Dropwizard

Tiger Tonic A Go framework for building JSON web services inspired by Dropwizard. If HTML is your game, this will hurt a little. Like the Go language

Dec 9, 2022
Simple and lightweight Go web framework inspired by koa
Simple and lightweight Go web framework inspired by koa

VOX A golang web framework for humans, inspired by Koa heavily. Getting started Installation Using the go get power: $ go get -u github.com/aisk/vox B

Dec 14, 2022
Rocinante is a gin inspired web framework built on top of net/http.

Rocinante Rocinante is a gin inspired web framework built on top of net/http. ⚙️ Installation $ go get -u github.com/fskanokano/rocinante-go ⚡️ Quicks

Jul 27, 2021
Gouweb: A web framework for go inspired by laravel

gouweb is a web framework for go inspired by laravel Installation go get -u gith

Feb 17, 2022
Go-igni: monolith-based web-framework in Go Inspired by classical PHP Frameworks like CodeIgnier & Laravel

go-igni Web Framework in Go About This is research project about developing monolith-based web-framework in Go Inspired by classical PHP Frameworks li

Feb 25, 2022
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.

Flamingo Framework Flamingo is a web framework based on Go. It is designed to build pluggable and maintainable web projects. It is production ready, f

Jan 5, 2023
Golanger Web Framework is a lightweight framework for writing web applications in Go.

/* Copyright 2013 Golanger.com. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except

Nov 14, 2022
The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework.

jin About The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework. If thi

Jul 14, 2022
⚡ Rux is an simple and fast web framework. support middleware, compatible http.Handler interface. 简单且快速的 Go web 框架,支持中间件,兼容 http.Handler 接口

Rux Simple and fast web framework for build golang HTTP applications. NOTICE: v1.3.x is not fully compatible with v1.2.x version Fast route match, sup

Dec 8, 2022
Roche is a Code Generator and Web Framework, makes web development super concise with Go, CleanArch
Roche is a Code Generator and Web Framework, makes web development super concise with Go, CleanArch

It is still under development, so please do not use it. We plan to release v.1.0.0 in the summer. roche is a web framework optimized for microservice

Sep 19, 2022
A powerful go web framework for highly scalable and resource efficient web application

webfr A powerful go web framework for highly scalable and resource efficient web application Installation: go get -u github.com/krishpranav/webfr Exa

Nov 28, 2021
A powerful go web framework for highly scalable and resource efficient web application

A powerful go web framework for highly scalable and resource efficient web application

Oct 3, 2022
A web app built using Go Buffalo web framework

Welcome to Buffalo Thank you for choosing Buffalo for your web development needs. Database Setup It looks like you chose to set up your application us

Feb 7, 2022
Gin is a HTTP web framework written in Go (Golang).
Gin is a HTTP web framework written in Go (Golang).

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

Jan 3, 2023
BANjO is a simple web framework written in Go (golang)

BANjO banjo it's a simple web framework for building simple web applications Install $ go get github.com/nsheremet/banjo Example Usage Simple Web App

Sep 27, 2022
Gearbox :gear: is a web framework written in Go with a focus on high performance
Gearbox :gear: is a web framework written in Go with a focus on high performance

gearbox ⚙️ is a web framework for building micro services written in Go with a focus on high performance. It's built on fasthttp which is up to 10x fa

Jan 3, 2023
Tigo is an HTTP web framework written in Go (Golang).It features a Tornado-like API with better performance. Tigo是一款用Go语言开发的web应用框架,API特性类似于Tornado并且拥有比Tornado更好的性能。
Tigo is an HTTP web framework written in Go (Golang).It features a Tornado-like API with better performance.  Tigo是一款用Go语言开发的web应用框架,API特性类似于Tornado并且拥有比Tornado更好的性能。

Tigo(For English Documentation Click Here) 一个使用Go语言开发的web框架。 相关工具及插件 tiger tiger是一个专门为Tigo框架量身定做的脚手架工具,可以使用tiger新建Tigo项目或者执行其他操作。

Jan 5, 2023
go-zero is a web and rpc framework written in Go. It's born to ensure the stability of the busy sites with resilient design. Builtin goctl greatly improves the development productivity.
go-zero is a web and rpc framework written in Go. It's born to ensure the stability of the busy sites with resilient design. Builtin goctl greatly improves the development productivity.

go-zero English | 简体中文 0. what is go-zero go-zero is a web and rpc framework that with lots of engineering practices builtin. It’s born to ensure the

Jan 2, 2023