github.com/gofiber/fiber/v2@v2.47.0/docs/api/app.md (about)

     1  ---
     2  id: app
     3  title: 🚀 App
     4  description: The app instance conventionally denotes the Fiber application.
     5  sidebar_position: 2
     6  ---
     7  
     8  import RoutingHandler from './../partials/routing/handler.md';
     9  
    10  ## Static
    11  
    12  Use the **Static** method to serve static files such as **images**, **CSS,** and **JavaScript**.
    13  
    14  :::info
    15  By default, **Static** will serve `index.html` files in response to a request on a directory.
    16  :::
    17  
    18  ```go title="Signature"
    19  func (app *App) Static(prefix, root string, config ...Static) Router
    20  ```
    21  
    22  Use the following code to serve files in a directory named `./public`
    23  
    24  ```go
    25  app.Static("/", "./public")
    26  
    27  // => http://localhost:3000/hello.html
    28  // => http://localhost:3000/js/jquery.js
    29  // => http://localhost:3000/css/style.css
    30  ```
    31  
    32  ```go title="Examples"
    33  // Serve files from multiple directories
    34  app.Static("/", "./public")
    35  
    36  // Serve files from "./files" directory:
    37  app.Static("/", "./files")
    38  ```
    39  
    40  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:
    41  
    42  ```go title="Examples"
    43  app.Static("/static", "./public")
    44  
    45  // => http://localhost:3000/static/hello.html
    46  // => http://localhost:3000/static/js/jquery.js
    47  // => http://localhost:3000/static/css/style.css
    48  ```
    49  
    50  If you want to have a little bit more control regarding the settings for serving static files. You could use the `fiber.Static` struct to enable specific settings.
    51  
    52  ```go title="fiber.Static{}"
    53  // Static defines configuration options when defining static assets.
    54  type Static struct {
    55      // When set to true, the server tries minimizing CPU usage by caching compressed files.
    56      // This works differently than the github.com/gofiber/compression middleware.
    57      // Optional. Default value false
    58      Compress bool `json:"compress"`
    59  
    60      // When set to true, enables byte range requests.
    61      // Optional. Default value false
    62      ByteRange bool `json:"byte_range"`
    63  
    64      // When set to true, enables directory browsing.
    65      // Optional. Default value false.
    66      Browse bool `json:"browse"`
    67  
    68      // When set to true, enables direct download.
    69      // Optional. Default value false.
    70      Download bool `json:"download"`
    71  
    72      // The name of the index file for serving a directory.
    73      // Optional. Default value "index.html".
    74      Index string `json:"index"`
    75  
    76      // Expiration duration for inactive file handlers.
    77      // Use a negative time.Duration to disable it.
    78      //
    79      // Optional. Default value 10 * time.Second.
    80      CacheDuration time.Duration `json:"cache_duration"`
    81  
    82      // The value for the Cache-Control HTTP-header
    83      // that is set on the file response. MaxAge is defined in seconds.
    84      //
    85      // Optional. Default value 0.
    86      MaxAge int `json:"max_age"`
    87  
    88      // ModifyResponse defines a function that allows you to alter the response.
    89      //
    90      // Optional. Default: nil
    91      ModifyResponse Handler
    92  
    93      // Next defines a function to skip this middleware when returned true.
    94      //
    95      // Optional. Default: nil
    96      Next func(c *Ctx) bool
    97  }
    98  ```
    99  
   100  ```go title="Example"
   101  // Custom config
   102  app.Static("/", "./public", fiber.Static{
   103    Compress:      true,
   104    ByteRange:     true,
   105    Browse:        true,
   106    Index:         "john.html",
   107    CacheDuration: 10 * time.Second,
   108    MaxAge:        3600,
   109  })
   110  ```
   111  
   112  ## Route Handlers
   113  
   114  <RoutingHandler />
   115  
   116  ## Mount
   117  
   118  You can Mount Fiber instance by creating a `*Mount`
   119  
   120  ```go title="Signature"
   121  func (a *App) Mount(prefix string, app *App) Router
   122  ```
   123  
   124  ```go title="Examples"
   125  func main() {
   126      app := fiber.New()
   127      micro := fiber.New()
   128      app.Mount("/john", micro) // GET /john/doe -> 200 OK
   129  
   130      micro.Get("/doe", func(c *fiber.Ctx) error {
   131          return c.SendStatus(fiber.StatusOK)
   132      })
   133  
   134      log.Fatal(app.Listen(":3000"))
   135  }
   136  ```
   137  
   138  ## MountPath
   139  
   140  The `MountPath` property contains one or more path patterns on which a sub-app was mounted.
   141  
   142  ```go title="Signature"
   143  func (app *App) MountPath() string
   144  ```
   145  
   146  ```go title="Examples"
   147  func main() {
   148  	app := fiber.New()
   149  	one := fiber.New()
   150  	two := fiber.New()
   151  	three := fiber.New()
   152  
   153  	two.Mount("/three", three)
   154  	one.Mount("/two", two)
   155  	app.Mount("/one", one)
   156    
   157  	one.MountPath()   // "/one"
   158  	two.MountPath()   // "/one/two"
   159  	three.MountPath() // "/one/two/three"
   160  	app.MountPath()   // ""
   161  }
   162  ```
   163  
   164  :::caution
   165  Mounting order is important for MountPath. If you want to get mount paths properly, you should start mounting from the deepest app.
   166  :::
   167  
   168  ## Group
   169  
   170  You can group routes by creating a `*Group` struct.
   171  
   172  ```go title="Signature"
   173  func (app *App) Group(prefix string, handlers ...Handler) Router
   174  ```
   175  
   176  ```go title="Examples"
   177  func main() {
   178    app := fiber.New()
   179  
   180    api := app.Group("/api", handler)  // /api
   181  
   182    v1 := api.Group("/v1", handler)   // /api/v1
   183    v1.Get("/list", handler)          // /api/v1/list
   184    v1.Get("/user", handler)          // /api/v1/user
   185  
   186    v2 := api.Group("/v2", handler)   // /api/v2
   187    v2.Get("/list", handler)          // /api/v2/list
   188    v2.Get("/user", handler)          // /api/v2/user
   189  
   190    log.Fatal(app.Listen(":3000"))
   191  }
   192  ```
   193  
   194  ## Route
   195  
   196  You can define routes with a common prefix inside the common function.
   197  
   198  ```go title="Signature"
   199  func (app *App) Route(prefix string, fn func(router Router), name ...string) Router
   200  ```
   201  
   202  ```go title="Examples"
   203  func main() {
   204    app := fiber.New()
   205  
   206    app.Route("/test", func(api fiber.Router) {
   207        api.Get("/foo", handler).Name("foo") // /test/foo (name: test.foo)
   208      api.Get("/bar", handler).Name("bar") // /test/bar (name: test.bar)
   209    }, "test.")
   210  
   211    log.Fatal(app.Listen(":3000"))
   212  }
   213  ```
   214  
   215  ## Server
   216  
   217  Server returns the underlying [fasthttp server](https://godoc.org/github.com/valyala/fasthttp#Server)
   218  
   219  ```go title="Signature"
   220  func (app *App) Server() *fasthttp.Server
   221  ```
   222  
   223  ```go title="Examples"
   224  func main() {
   225      app := fiber.New()
   226  
   227      app.Server().MaxConnsPerIP = 1
   228  
   229      // ...
   230  }
   231  ```
   232  
   233  ## Server Shutdown
   234  
   235  Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners and then waits indefinitely for all connections to return to idle before shutting down.
   236  
   237  ShutdownWithTimeout will forcefully close any active connections after the timeout expires.
   238  
   239  ShutdownWithContext shuts down the server including by force if the context's deadline is exceeded.
   240  
   241  ```go
   242  func (app *App) Shutdown() error
   243  func (app *App) ShutdownWithTimeout(timeout time.Duration) error
   244  func (app *App) ShutdownWithContext(ctx context.Context) error
   245  ```
   246  
   247  ## HandlersCount
   248  
   249  This method returns the amount of registered handlers.
   250  
   251  ```go title="Signature"
   252  func (app *App) HandlersCount() uint32
   253  ```
   254  
   255  ## Stack
   256  
   257  This method returns the original router stack
   258  
   259  ```go title="Signature"
   260  func (app *App) Stack() [][]*Route
   261  ```
   262  
   263  ```go title="Examples"
   264  var handler = func(c *fiber.Ctx) error { return nil }
   265  
   266  func main() {
   267      app := fiber.New()
   268  
   269      app.Get("/john/:age", handler)
   270      app.Post("/register", handler)
   271  
   272      data, _ := json.MarshalIndent(app.Stack(), "", "  ")
   273      fmt.Println(string(data))
   274  
   275      app.Listen(":3000")
   276  }
   277  ```
   278  
   279  ```javascript title="Result"
   280  [
   281    [
   282      {
   283        "method": "GET",
   284        "path": "/john/:age",
   285        "params": [
   286          "age"
   287        ]
   288      }
   289    ],
   290    [
   291      {
   292        "method": "HEAD",
   293        "path": "/john/:age",
   294        "params": [
   295          "age"
   296        ]
   297      }
   298    ],
   299    [
   300      {
   301        "method": "POST",
   302        "path": "/register",
   303        "params": null
   304      }
   305    ]
   306  ]
   307  ```
   308  
   309  ## Name
   310  
   311  This method assigns the name of latest created route.
   312  
   313  ```go title="Signature"
   314  func (app *App) Name(name string) Router
   315  ```
   316  
   317  ```go title="Examples"
   318  var handler = func(c *fiber.Ctx) error { return nil }
   319  
   320  func main() {
   321      app := fiber.New()
   322  
   323      app.Get("/", handler)
   324      app.Name("index")
   325  
   326      app.Get("/doe", handler).Name("home")
   327  
   328      app.Trace("/tracer", handler).Name("tracert")
   329  
   330      app.Delete("/delete", handler).Name("delete")
   331  
   332      a := app.Group("/a")
   333      a.Name("fd.")
   334  
   335      a.Get("/test", handler).Name("test")
   336  
   337      data, _ := json.MarshalIndent(app.Stack(), "", "  ")
   338      fmt.Print(string(data))
   339  
   340      app.Listen(":3000")
   341  
   342  }
   343  ```
   344  
   345  ```javascript title="Result"
   346  [
   347    [
   348      {
   349        "method": "GET",
   350        "name": "index",
   351        "path": "/",
   352        "params": null
   353      },
   354      {
   355        "method": "GET",
   356        "name": "home",
   357        "path": "/doe",
   358        "params": null
   359      },
   360      {
   361        "method": "GET",
   362        "name": "fd.test",
   363        "path": "/a/test",
   364        "params": null
   365      }
   366    ],
   367    [
   368      {
   369        "method": "HEAD",
   370        "name": "",
   371        "path": "/",
   372        "params": null
   373      },
   374      {
   375        "method": "HEAD",
   376        "name": "",
   377        "path": "/doe",
   378        "params": null
   379      },
   380      {
   381        "method": "HEAD",
   382        "name": "",
   383        "path": "/a/test",
   384        "params": null
   385      }
   386    ],
   387    null,
   388    null,
   389    [
   390      {
   391        "method": "DELETE",
   392        "name": "delete",
   393        "path": "/delete",
   394        "params": null
   395      }
   396    ],
   397    null,
   398    null,
   399    [
   400      {
   401        "method": "TRACE",
   402        "name": "tracert",
   403        "path": "/tracer",
   404        "params": null
   405      }
   406    ],
   407    null
   408  ]
   409  ```
   410  
   411  ## GetRoute
   412  
   413  This method gets the route by name.
   414  
   415  ```go title="Signature"
   416  func (app *App) GetRoute(name string) Route
   417  ```
   418  
   419  ```go title="Examples"
   420  var handler = func(c *fiber.Ctx) error { return nil }
   421  
   422  func main() {
   423      app := fiber.New()
   424  
   425      app.Get("/", handler).Name("index")
   426      
   427      data, _ := json.MarshalIndent(app.GetRoute("index"), "", "  ")
   428  	fmt.Print(string(data))
   429  
   430  
   431  	app.Listen(":3000")
   432  
   433  }
   434  ```
   435  
   436  ```javascript title="Result"
   437  {
   438    "method": "GET",
   439    "name": "index",
   440    "path": "/",
   441    "params": null
   442  }
   443  ```
   444  
   445  ## GetRoutes
   446  
   447  This method gets all routes.
   448  
   449  ```go title="Signature"
   450  func (app *App) GetRoutes(filterUseOption ...bool) []Route
   451  ```
   452  
   453  When filterUseOption equal to true, it will filter the routes registered by the middleware.
   454  ```go title="Examples"
   455  func main() {
   456  	app := fiber.New()
   457  	app.Post("/", func (c *fiber.Ctx) error {
   458  		return c.SendString("Hello, World!")
   459  	}).Name("index")
   460  	data, _ := json.MarshalIndent(app.GetRoutes(true), "", "  ")
   461  	fmt.Print(string(data))
   462  }
   463  ```
   464  
   465  ```javascript title="Result"
   466  [
   467      {
   468          "method": "POST",
   469          "name": "index",
   470          "path": "/",
   471          "params": null
   472      }
   473  ]
   474  ```
   475  
   476  ## Config
   477  
   478  Config returns the app config as value \( read-only \).
   479  
   480  ```go title="Signature"
   481  func (app *App) Config() Config
   482  ```
   483  
   484  ## Handler
   485  
   486  Handler returns the server handler that can be used to serve custom \*fasthttp.RequestCtx requests.
   487  
   488  ```go title="Signature"
   489  func (app *App) Handler() fasthttp.RequestHandler
   490  ```
   491  
   492  ## Listen
   493  
   494  Listen serves HTTP requests from the given address.
   495  
   496  ```go title="Signature"
   497  func (app *App) Listen(addr string) error
   498  ```
   499  
   500  ```go title="Examples"
   501  // Listen on port :8080 
   502  app.Listen(":8080")
   503  
   504  // Custom host
   505  app.Listen("127.0.0.1:8080")
   506  ```
   507  
   508  ## ListenTLS
   509  
   510  ListenTLS serves HTTPs requests from the given address using certFile and keyFile paths to as TLS certificate and key file.
   511  
   512  ```go title="Signature"
   513  func (app *App) ListenTLS(addr, certFile, keyFile string) error
   514  ```
   515  
   516  ```go title="Examples"
   517  app.ListenTLS(":443", "./cert.pem", "./cert.key");
   518  ```
   519  
   520  Using `ListenTLS` defaults to the following config \( use `Listener` to provide your own config \)
   521  
   522  ```go title="Default \*tls.Config"
   523  &tls.Config{
   524      MinVersion:               tls.VersionTLS12,
   525      Certificates: []tls.Certificate{
   526          cert,
   527      },
   528  }
   529  ```
   530  
   531  ## ListenTLSWithCertificate
   532  
   533  ```go title="Signature"
   534  func (app *App) ListenTLS(addr string, cert tls.Certificate) error
   535  ```
   536  
   537  ```go title="Examples"
   538  app.ListenTLSWithCertificate(":443", cert);
   539  ```
   540  
   541  Using `ListenTLSWithCertificate` defaults to the following config \( use `Listener` to provide your own config \)
   542  
   543  ```go title="Default \*tls.Config"
   544  &tls.Config{
   545      MinVersion:               tls.VersionTLS12,
   546      Certificates: []tls.Certificate{
   547          cert,
   548      },
   549  }
   550  ```
   551  
   552  ## ListenMutualTLS
   553  
   554  ListenMutualTLS serves HTTPs requests from the given address using certFile, keyFile and clientCertFile are the paths to TLS certificate and key file
   555  
   556  ```go title="Signature"
   557  func (app *App) ListenMutualTLS(addr, certFile, keyFile, clientCertFile string) error
   558  ```
   559  
   560  ```go title="Examples"
   561  app.ListenMutualTLS(":443", "./cert.pem", "./cert.key", "./ca-chain-cert.pem");
   562  ```
   563  
   564  Using `ListenMutualTLS` defaults to the following config \( use `Listener` to provide your own config \)
   565  
   566  ```go title="Default \*tls.Config"
   567  &tls.Config{
   568  	MinVersion: tls.VersionTLS12,
   569  	ClientAuth: tls.RequireAndVerifyClientCert,
   570  	ClientCAs:  clientCertPool,
   571  	Certificates: []tls.Certificate{
   572  		cert,
   573  	},
   574  }
   575  ```
   576  
   577  ## ListenMutualTLSWithCertificate
   578  
   579  ListenMutualTLSWithCertificate serves HTTPs requests from the given address using certFile, keyFile and clientCertFile are the paths to TLS certificate and key file
   580  
   581  ```go title="Signature"
   582  func (app *App) ListenMutualTLSWithCertificate(addr string, cert tls.Certificate, clientCertPool *x509.CertPool) error
   583  ```
   584  
   585  ```go title="Examples"
   586  app.ListenMutualTLSWithCertificate(":443", cert, clientCertPool);
   587  ```
   588  
   589  Using `ListenMutualTLSWithCertificate` defaults to the following config \( use `Listener` to provide your own config \)
   590  
   591  ```go title="Default \*tls.Config"
   592  &tls.Config{
   593  	MinVersion: tls.VersionTLS12,
   594  	ClientAuth: tls.RequireAndVerifyClientCert,
   595  	ClientCAs:  clientCertPool,
   596  	Certificates: []tls.Certificate{
   597  		cert,
   598  	},
   599  }
   600  ```
   601  
   602  ## Listener
   603  
   604  You can pass your own [`net.Listener`](https://pkg.go.dev/net/#Listener) using the `Listener` method. This method can be used to enable **TLS/HTTPS** with a custom tls.Config.
   605  
   606  ```go title="Signature"
   607  func (app *App) Listener(ln net.Listener) error
   608  ```
   609  
   610  ```go title="Examples"
   611  ln, _ := net.Listen("tcp", ":3000")
   612  
   613  cer, _:= tls.LoadX509KeyPair("server.crt", "server.key")
   614  
   615  ln = tls.NewListener(ln, &tls.Config{Certificates: []tls.Certificate{cer}})
   616  
   617  app.Listener(ln)
   618  ```
   619  
   620  ## Test
   621  
   622  Testing your application is done with the **Test** method. Use this method for creating `_test.go` files or when you need to debug your routing logic. The default timeout is `1s` if you want to disable a timeout altogether, pass `-1` as a second argument.
   623  
   624  ```go title="Signature"
   625  func (app *App) Test(req *http.Request, msTimeout ...int) (*http.Response, error)
   626  ```
   627  
   628  ```go title="Examples"
   629  // Create route with GET method for test:
   630  app.Get("/", func(c *fiber.Ctx) error {
   631    fmt.Println(c.BaseURL())              // => http://google.com
   632    fmt.Println(c.Get("X-Custom-Header")) // => hi
   633  
   634    return c.SendString("hello, World!")
   635  })
   636  
   637  // http.Request
   638  req := httptest.NewRequest("GET", "http://google.com", nil)
   639  req.Header.Set("X-Custom-Header", "hi")
   640  
   641  // http.Response
   642  resp, _ := app.Test(req)
   643  
   644  // Do something with results:
   645  if resp.StatusCode == fiber.StatusOK {
   646    body, _ := ioutil.ReadAll(resp.Body)
   647    fmt.Println(string(body)) // => Hello, World!
   648  }
   649  ```
   650  
   651  ## Hooks
   652  
   653  Hooks is a method to return [hooks](../guide/hooks.md) property.
   654  
   655  ```go title="Signature"
   656  func (app *App) Hooks() *Hooks
   657  ```