fiber

package module
v1.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 10, 2020 License: MIT Imports: 28 Imported by: 1,263

README

Fiberru ch

Fiber is an Expressjs inspired web framework build 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.

⚡️ Quick start

package main

import "github.com/gofiber/fiber"

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

  app.Get("/", func(c *fiber.Ctx) {
    c.Send("Hello, World!")
  })

  app.Listen(3000)
}

⚙️ Installation

First of all, download and install Go. 1.11 or higher is required.

Installation is done using the go get command:

go get github.com/gofiber/fiber

🤖 Benchmarks

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

🎯 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 follow UNIX way, so that new gophers can quickly enter the world of Go with a warm and trusted welcome.

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

👀 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 API documentation.

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.Listen(3000)
}

Routing

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

  // GET /john
  app.Get("/:name", func(c *fiber.Ctx) {
    fmt.Printf("Hello %s!", c.Params("name"))
    // => Hello john!
  })

  // GET /john
  app.Get("/:name/:age?", func(c *fiber.Ctx) {
    fmt.Printf("Name: %s, Age: %s", c.Params("name"), c.Params("age"))
    // => Name: john, Age:
  })

  // GET /api/register
  app.Get("/api*", func(c *fiber.Ctx) {
    fmt.Printf("/api%s", c.Params("*"))
    // => /api/register
  })

  app.Listen(3000)
}

Middleware

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

  // Match any post route
  app.Post(func(c *fiber.Ctx) {
    user, pass, ok := c.BasicAuth()
    if !ok || user != "john" || pass != "doe" {
      c.Status(403).Send("Sorry John")
      return
    }
    c.Next()
  })

  // Match all routes starting with /api
  app.Use("/api", func(c *fiber.Ctx) {
    c.Set("Access-Control-Allow-Origin", "*")
    c.Set("Access-Control-Allow-Headers", "X-Requested-With")
    c.Next()
  })

  // Optional param
  app.Post("/api/register", func(c *fiber.Ctx) {
    username := c.Body("username")
    password := c.Body("password")
    // ..
  })

  app.Listen(3000)
}

404 Handling

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

  // Serve static files from "public" directory
  app.Static("./public")

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

  app.Listen(3000)
}

JSON Response

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

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

  // Serialize JSON
  app.Get("/json", func (c *fiber.Ctx) {
    c.JSON(&User{"John", 20})
  })

  app.Listen(3000)
}

💬 Media

👍 Contribute

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

  1. Add a GitHub Star to project.
  2. Tweet about project on your Twitter.
  3. Write a review or tutorial on Medium, Dev.to or personal blog.
  4. Help us to translate this README and API Docs to another language.

Buy Me A Coffee

⭐️ Stars

Stars over time

⚠️ License

Fiber is free and open-source software licensed under the MIT License.

Documentation

Index

Constants

View Source
const (
	// Version : Fiber version
	Version = "1.4.2"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cookie struct {
	Expire int // time.Unix(1578981376, 0)
	MaxAge int
	Domain string
	Path   string

	HTTPOnly bool
	Secure   bool
	SameSite string
}

Cookie : struct

type Ctx

type Ctx struct {
	Fasthttp *fasthttp.RequestCtx
	// contains filtered or unexported fields
}

Ctx : struct

func (*Ctx) Accepts

func (ctx *Ctx) Accepts(offers ...string) string

Accepts : https://fiber.wiki/context#accepts

func (*Ctx) AcceptsCharsets

func (ctx *Ctx) AcceptsCharsets(offers ...string) string

AcceptsCharsets : https://fiber.wiki/context#acceptscharsets

func (*Ctx) AcceptsEncodings

func (ctx *Ctx) AcceptsEncodings(offers ...string) string

AcceptsEncodings : https://fiber.wiki/context#acceptsencodings

func (*Ctx) AcceptsLanguages

func (ctx *Ctx) AcceptsLanguages(offers ...string) string

AcceptsLanguages : https://fiber.wiki/context#acceptslanguages

func (*Ctx) Append

func (ctx *Ctx) Append(field string, values ...string)

Append : https://fiber.wiki/context#append

func (*Ctx) Attachment

func (ctx *Ctx) Attachment(name ...string)

Attachment : https://fiber.wiki/context#attachment

func (*Ctx) BaseURL added in v1.0.0

func (ctx *Ctx) BaseURL() string

BaseURL : https://fiber.wiki/context#baseurl

func (*Ctx) BaseUrl

func (ctx *Ctx) BaseUrl() string

BaseUrl : https://fiber.wiki/context#baseurl

func (*Ctx) BasicAuth

func (ctx *Ctx) BasicAuth() (user, pass string, ok bool)

BasicAuth : https://fiber.wiki/context#basicauth

func (*Ctx) Body

func (ctx *Ctx) Body(args ...interface{}) string

Body : https://fiber.wiki/context#body

func (*Ctx) BodyParser added in v1.0.0

func (ctx *Ctx) BodyParser(v interface{}) error

BodyParser : https://fiber.wiki/context#bodyparser

func (*Ctx) ClearCookie

func (ctx *Ctx) ClearCookie(name ...string)

ClearCookie : https://fiber.wiki/context#clearcookie

func (*Ctx) Cookie

func (ctx *Ctx) Cookie(key, value string, options ...interface{})

Cookie : https://fiber.wiki/context#cookie

func (*Ctx) Cookies

func (ctx *Ctx) Cookies(args ...interface{}) string

Cookies : https://fiber.wiki/context#cookies

func (*Ctx) Download

func (ctx *Ctx) Download(file string, name ...string)

Download : https://fiber.wiki/context#download

func (*Ctx) End

func (ctx *Ctx) End()

End : https://fiber.wiki/context#end

func (*Ctx) FormFile

func (ctx *Ctx) FormFile(key string) (*multipart.FileHeader, error)

FormFile : https://fiber.wiki/context#formfile

func (*Ctx) FormValue

func (ctx *Ctx) FormValue(key string) string

FormValue : https://fiber.wiki/context#formvalue

func (*Ctx) Format

func (ctx *Ctx) Format(args ...interface{})

Format : https://fiber.wiki/context#format

func (*Ctx) Fresh

func (ctx *Ctx) Fresh() bool

Fresh : https://fiber.wiki/context#fresh

func (*Ctx) Get

func (ctx *Ctx) Get(key string) string

Get : https://fiber.wiki/context#get

func (*Ctx) HeadersSent

func (ctx *Ctx) HeadersSent()

HeadersSent : https://fiber.wiki/context#headerssent

func (*Ctx) Hostname

func (ctx *Ctx) Hostname() string

Hostname : https://fiber.wiki/context#hostname

func (*Ctx) IP added in v1.0.0

func (ctx *Ctx) IP() string

IP : https://fiber.wiki/context#Ip

func (*Ctx) IPs added in v1.0.0

func (ctx *Ctx) IPs() []string

IPs : https://fiber.wiki/context#ips

func (*Ctx) Ip

func (ctx *Ctx) Ip() string

Ip is deprecated, this will be removed in v2: Use c.IP() instead

func (*Ctx) Ips

func (ctx *Ctx) Ips() []string

Ips is deprecated, this will be removed in v2: Use c.IPs() instead

func (*Ctx) Is

func (ctx *Ctx) Is(ext string) bool

Is : https://fiber.wiki/context#is

func (*Ctx) JSON added in v1.0.0

func (ctx *Ctx) JSON(v interface{}) error

JSON : https://fiber.wiki/context#json

func (*Ctx) JSONBytes added in v1.3.1

func (ctx *Ctx) JSONBytes(raw []byte)

JSONBytes : https://fiber.wiki/context#jsonbytes

func (*Ctx) JSONP added in v1.0.0

func (ctx *Ctx) JSONP(v interface{}, cb ...string) error

JSONP : https://fiber.wiki/context#jsonp

func (*Ctx) JSONString added in v1.3.1

func (ctx *Ctx) JSONString(raw string)

JSONString : https://fiber.wiki/context#json

func (*Ctx) Json

func (ctx *Ctx) Json(v interface{}) error

Json is deprecated, this will be removed in v2: Use c.JSON() instead

func (*Ctx) JsonBytes added in v1.2.3

func (ctx *Ctx) JsonBytes(raw []byte)

JsonBytes is deprecated, this will be removed in v2: Use c.JSONBytes() instead

func (*Ctx) JsonString added in v1.2.3

func (ctx *Ctx) JsonString(raw string)

JsonString is deprecated, this will be removed in v2: Use c.JSONString() instead

func (*Ctx) Jsonp

func (ctx *Ctx) Jsonp(v interface{}, cb ...string) error

Jsonp is deprecated, this will be removed in v2: Use c.JSONP() instead

func (ctx *Ctx) Links(link ...string)

Links : https://fiber.wiki/context#links

func (*Ctx) Locals

func (ctx *Ctx) Locals(key string, val ...interface{}) interface{}

Locals : https://fiber.wiki/context#locals

func (*Ctx) Location

func (ctx *Ctx) Location(path string)

Location : https://fiber.wiki/context#location

func (*Ctx) Method

func (ctx *Ctx) Method() string

Method : https://fiber.wiki/context#method

func (*Ctx) MultipartForm

func (ctx *Ctx) MultipartForm() (*multipart.Form, error)

MultipartForm : https://fiber.wiki/context#multipartform

func (*Ctx) Next

func (ctx *Ctx) Next()

Next : https://fiber.wiki/context#next

func (*Ctx) OriginalURL added in v1.0.0

func (ctx *Ctx) OriginalURL() string

OriginalURL : https://fiber.wiki/context#originalurl

func (*Ctx) OriginalUrl

func (ctx *Ctx) OriginalUrl() string

OriginalUrl is deprecated, this will be removed in v2: Use c.OriginalURL() instead

func (*Ctx) Params

func (ctx *Ctx) Params(key string) string

Params : https://fiber.wiki/context#params

func (*Ctx) Path

func (ctx *Ctx) Path() string

Path : https://fiber.wiki/context#path

func (*Ctx) Protocol

func (ctx *Ctx) Protocol() string

Protocol : https://fiber.wiki/context#protocol

func (*Ctx) Query

func (ctx *Ctx) Query(key string) string

Query : https://fiber.wiki/context#query

func (*Ctx) Range

func (ctx *Ctx) Range()

Range : https://fiber.wiki/context#range

func (*Ctx) Redirect

func (ctx *Ctx) Redirect(path string, status ...int)

Redirect : https://fiber.wiki/context#redirect

func (*Ctx) Render

func (ctx *Ctx) Render()

Render : https://fiber.wiki/context#render

func (*Ctx) Route

func (ctx *Ctx) Route() *Route

Route : https://fiber.wiki/context#route

func (*Ctx) SaveFile added in v1.0.0

func (ctx *Ctx) SaveFile(fh *multipart.FileHeader, path string) error

SaveFile : https://fiber.wiki/context#secure

func (*Ctx) Secure

func (ctx *Ctx) Secure() bool

Secure : https://fiber.wiki/context#secure

func (*Ctx) Send

func (ctx *Ctx) Send(args ...interface{})

Send : https://fiber.wiki/context#send

func (*Ctx) SendBytes

func (ctx *Ctx) SendBytes(body []byte)

SendBytes : https://fiber.wiki/context#sendbytes

func (*Ctx) SendFile

func (ctx *Ctx) SendFile(file string, gzip ...bool)

SendFile : https://fiber.wiki/context#sendfile

func (*Ctx) SendStatus

func (ctx *Ctx) SendStatus(status int)

SendStatus : https://fiber.wiki/context#sendstatus

func (*Ctx) SendString

func (ctx *Ctx) SendString(body string)

SendString : https://fiber.wiki/context#sendstring

func (*Ctx) Set

func (ctx *Ctx) Set(key string, val string)

Set : https://fiber.wiki/context#set

func (*Ctx) SignedCookies

func (ctx *Ctx) SignedCookies()

SignedCookies : https://fiber.wiki/context#signedcookies

func (*Ctx) Stale

func (ctx *Ctx) Stale() bool

Stale : https://fiber.wiki/context#stale

func (*Ctx) Status

func (ctx *Ctx) Status(status int) *Ctx

Status : https://fiber.wiki/context#status

func (*Ctx) Subdomains

func (ctx *Ctx) Subdomains(offset ...int) (subs []string)

Subdomains : https://fiber.wiki/context#subdomains

func (*Ctx) Type

func (ctx *Ctx) Type(ext string) *Ctx

Type : https://fiber.wiki/context#type

func (*Ctx) Vary

func (ctx *Ctx) Vary(fields ...string)

Vary : https://fiber.wiki/context#vary

func (*Ctx) Write

func (ctx *Ctx) Write(args ...interface{})

Write : https://fiber.wiki/context#write

func (*Ctx) XHR added in v1.0.0

func (ctx *Ctx) XHR() bool

XHR : https://fiber.wiki/context#xhr

func (*Ctx) XML added in v1.3.1

func (ctx *Ctx) XML(v interface{}) error

XML : https://fiber.wiki/context#xml

func (*Ctx) Xhr

func (ctx *Ctx) Xhr() bool

Xhr is deprecated, this will be removed in v2: Use c.XHR() instead

func (*Ctx) Xml added in v1.1.0

func (ctx *Ctx) Xml(v interface{}) error

Xml is deprecated, this will be removed in v2: Use c.XML() instead

type Fiber

type Fiber struct {
	// Server name header
	Server string

	// Show fiber banner
	Banner bool
	// https://github.com/valyala/fasthttp/blob/master/server.go#L150
	Engine *engine
	// https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
	Prefork bool
	// contains filtered or unexported fields
}

Fiber structure

func (*Fiber) All

func (f *Fiber) All(args ...interface{}) *Fiber

All matches any HTTP method

func (*Fiber) Connect

func (f *Fiber) Connect(args ...interface{}) *Fiber

Connect establishes a tunnel to the server identified by the target resource.

func (*Fiber) Delete

func (f *Fiber) Delete(args ...interface{}) *Fiber

Delete deletes the specified resource.

func (*Fiber) Get

func (f *Fiber) Get(args ...interface{}) *Fiber

Get requests a representation of the specified resource. Requests using GET should only retrieve data.

func (*Fiber) Group added in v1.4.2

func (f *Fiber) Group(path string) *Group

Group :

func (*Fiber) Head

func (f *Fiber) Head(args ...interface{}) *Fiber

Head asks for a response identical to that of a GET request, but without the response body.

func (*Fiber) Listen

func (f *Fiber) Listen(address interface{}, tls ...string)

Listen : https://fiber.wiki/application#listen

func (*Fiber) Options

func (f *Fiber) Options(args ...interface{}) *Fiber

Options is used to describe the communication options for the target resource.

func (*Fiber) Patch

func (f *Fiber) Patch(args ...interface{}) *Fiber

Patch is used to apply partial modifications to a resource.

func (*Fiber) Post

func (f *Fiber) Post(args ...interface{}) *Fiber

Post is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

func (*Fiber) Put

func (f *Fiber) Put(args ...interface{}) *Fiber

Put replaces all current representations of the target resource with the request payload.

func (*Fiber) Shutdown added in v1.4.1

func (f *Fiber) Shutdown() error

Shutdown server gracefully

func (*Fiber) Static

func (f *Fiber) Static(args ...string)

Static https://fiber.wiki/application#static

func (*Fiber) Test added in v1.4.0

func (f *Fiber) Test(req *http.Request) (*http.Response, error)

Test takes a http.Request and execute a fake connection to the application It returns a http.Response when the connection was successfull

func (*Fiber) Trace

func (f *Fiber) Trace(args ...interface{}) *Fiber

Trace performs a message loop-back test along the path to the target resource.

func (*Fiber) Use

func (f *Fiber) Use(args ...interface{}) *Fiber

Use only matches the starting path

type Group added in v1.0.0

type Group struct {
	// contains filtered or unexported fields
}

Group :

func (*Group) All added in v1.0.0

func (g *Group) All(args ...interface{}) *Group

All for group

func (*Group) Connect added in v1.0.0

func (g *Group) Connect(args ...interface{}) *Group

Connect for group

func (*Group) Delete added in v1.0.0

func (g *Group) Delete(args ...interface{}) *Group

Delete for group

func (*Group) Get added in v1.0.0

func (g *Group) Get(args ...interface{}) *Group

Get for group

func (*Group) Head added in v1.0.0

func (g *Group) Head(args ...interface{}) *Group

Head for group

func (*Group) Options added in v1.0.0

func (g *Group) Options(args ...interface{}) *Group

Options for group

func (*Group) Patch added in v1.0.0

func (g *Group) Patch(args ...interface{}) *Group

Patch for group

func (*Group) Post added in v1.0.0

func (g *Group) Post(args ...interface{}) *Group

Post for group

func (*Group) Put added in v1.0.0

func (g *Group) Put(args ...interface{}) *Group

Put for group

func (*Group) Trace added in v1.0.0

func (g *Group) Trace(args ...interface{}) *Group

Trace for group

func (*Group) Use added in v1.0.0

func (g *Group) Use(args ...interface{}) *Group

Use for group

type Route added in v1.0.0

type Route struct {
	// HTTP method in uppercase, can be a * for Use() & All()
	Method string
	// Stores the original path
	Path string
	// Bool that defines if the route is a Use() middleware
	Midware bool
	// wildcard bool is for routes without a path, * and /*
	Wildcard bool
	// Stores compiled regex special routes :params, *wildcards, optionals?
	Regex *regexp.Regexp
	// Store params if special routes :params, *wildcards, optionals?
	Params []string
	// Callback function for specific route
	Handler func(*Ctx)
}

Route : struct

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳