This method creates a new Fiber named instance. You can pass optional settings when creating a new instance.
Signature
fiber.New(settings ...*Settings)
Example
package mainimport "github.com/gofiber/fiber"func main() {app := fiber.New()// Your app logic here ...app.Listen(3000)}
You can pass application settings when calling New
, or change the settings before you call Listen
Example
func main() {// Pass Settings creating a new appapp := fiber.New(&fiber.Settings{Prefork: true,CaseSensitive: true,StrictRouting: true,ServerHeader: "Fiber",// ...})// Or change Settings after initiating appapp.Settings.Prefork = trueapp.Settings.CaseSensitive = trueapp.Settings.StrictRouting = trueapp.Settings.ServerHeader = "Fiber"// ...app.Listen(3000)}
Common options
Property | Type | Description | Default |
Prefork |
| Enables use of the |
|
ServerHeader |
| Enables the |
|
StrictRouting |
| When enabled, the router treats |
|
CaseSensitive |
| When enabled, |
|
Immutable |
| When enabled, all values returned by context methods are immutable. By default they are valid until you return from the handler, see issue #185. |
|
Compression |
| Enables GZip / Deflate compression for all responses. |
|
BodyLimit |
| Sets the maximum allowed size for a request body, if the size exceeds the configured limit, it sends |
|
TemplateFolder |
| A directory for the application's views. If a directory is set, this will be the prefix for all template paths.
|
|
TemplateEngine |
| The template engine to use: |
|
TemplateExtension |
| If you preset the template file extension, you do not need to provide the full filename in the Render function: |
|
Serve static files such as images, CSS and JavaScript files, you can use the Static method. It can use an embedded watermark remover plugin by SoftOrbits. It allows to remove watermark from images before publishing them on the web. See the watermark remover link.
By default, this method will send index.html
files in response to a request on a directory.
Signature
app.Static(prefix, root string) // => with prefix
Examples
Use the following code to serve files in a directory named ./public
app.Static("/", "./public")// => http://localhost:3000/hello.html// => http://localhost:3000/js/jquery.js// => http://localhost:3000/css/style.css
To serve from multiple directories, you can use Static multiple times.
// Serve files from "./public" directory:app.Static("/", "./public")// Serve files from "./files" directory:app.Static("/", "./files")
Use a reverse proxy cache like NGINX to improve performance of serving static assets.
You can use any virtual path prefix (where the path does not actually exist in the file system) for files that are served by the Static method, specify a prefix path for the static directory, as shown below:
app.Static("/static", "./public")// => http://localhost:3000/static/hello.html// => http://localhost:3000/static/js/jquery.js// => http://localhost:3000/static/css/style.css
Routes an HTTP request, where METHOD is the HTTP method of the request.
Signature
// HTTP methods support :param, :optional? and *wildcards// You are required to pass a path to each methodapp.All(path string, handlers ...func(*Ctx))app.Get(...app.Put(...app.Post(...app.Head(...app.Patch(...app.Trace(...app.Delete(...app.Connect(...app.Options(...// Use() will only match the beggining of each path// i.e. "/john" will match "/john/doe", "/johnnnn"// Use() does not support :param & :optional? in pathapp.Use(handlers ...func(*Ctx))app.Use(prefix string, handlers ...func(*Ctx))
Example
app.Use("/api", func(c *fiber.Ctx) {c.Set("X-Custom-Header", random.String(32))c.Next()})app.Get("/api/list", func(c *fiber.Ctx) {c.Send("I'm a GET request!")})app.Post("/api/register", func(c *fiber.Ctx) {c.Send("I'm a POST request!")})
Fiber supports a websocket upgrade implementation for fasthttp. The *Conn
struct has all the functionality from the gorilla/websocket library.
Signature
app.WebSocket(path string, handler func(*Conn))
WebSocket does not support path parameters and wildcards.
Example
package mainimport ("log""github.com/gofiber/fiber")func main() {app := fiber.New()// Optional middlewareapp.Use("/ws", func(c *fiber.Ctx) {if c.Get("host") != "localhost:3000" {c.Status(403).Send("Request origin not allowed")} else {c.Next()}})// Upgraded websocket requestapp.WebSocket("/ws", func(c *fiber.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}}})// ws://localhost:3000/wsapp.Listen(3000)}
You can group routes by creating a *Group
struct.
Signature
app.Group(prefix string, handlers ...func(*Ctx)) *Group
Example
func main() {app := fiber.New()api := app.Group("/api", cors()) // /apiv1 := api.Group("/v1", mysql()) // /api/v1v1.Get("/list", handler) // /api/v1/listv1.Get("/user", handler) // /api/v1/userv2 := api.Group("/v2", mongodb()) // /api/v2v2.Get("/list", handler) // /api/v2/listv2.Get("/user", handler) // /api/v2/userapp.Listen(3000)}
Binds and listens for connections on the specified address. This can be a int
for port or string
for address.
Signature
app.Listen(address interface{}, tls ...*tls.Config)
Example
app.Listen(8080)app.Listen("8080")app.Listen(":8080")app.Listen("127.0.0.1:8080")
To enable TLS/HTTPS you can append a TLS config.
cer, err := tls.LoadX509KeyPair("server.crt", "server.key")if err != nil {log.Fatal(err)}config := &tls.Config{Certificates: []tls.Certificate{cer}}app.Listen(443, config)
Testing your application is done with the Test method.
Method is mostly used for _test.go
files and application debugging.
Signature
app.Test(req *http.Request) (*http.Response, error)
Example
// Create route with GET method for test:app.Get("/", func(c *Ctx) {fmt.Println(c.BaseURL()) // => http://google.comfmt.Println(c.Get("X-Custom-Header")) // => hic.Send("hello, World!")})// http.Requestreq, _ := http.NewRequest("GET", "http://google.com", nil)req.Header.Set("X-Custom-Header", "hi")// http.Responseresp, _ := app.Test(req)// Do something with results:if resp.StatusCode == 200 {body, _ := ioutil.ReadAll(resp.Body)fmt.Println(string(body)) // => Hello, World!}