fiber/docs/application.md

3.1 KiB

Application

The app object conventionally denotes the Fiber application.

Initialize

Creates an Fiber instance name "app"

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

TLS

To enable TLS you need to provide a certkey and certfile.

// Enable TLS
app := fiber.New()

app.CertKey("./cert.key")
app.CertFile("./cert.pem")

app.Listen(443)

Fasthttp

You can pass some Fasthttp server settings via the Fiber instance.
Make sure that you set these settings before calling the Listen method. You can find the description of each property in Fasthttp server settings

!>Only change these settings if you know what you are doing.

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

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.

// Function signature
app.Connect(...)
app.Delete(...)
app.Get(...)
app.Head(...)
app.Options(...)
app.Patch(...)
app.Post(...)
app.Put(...)
app.Trace(...)
// Matches all HTTP verbs
// Use & All are the same function
app.Use(...)
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

go run main.go -prefork
# Or on build
./main -prefork

You can also enable preforking within the application.

// 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)

Listen

Binds and listens for connections on the specified host and port.

// Function signature
app.Listen(port int, addr ...string)


// Example
app.Listen(8080)
app.Listen(8080, "127.0.0.1")

Caught a mistake? Edit this page on GitHub!